Repository navigation
Expand file tree
/
Copy pathMergeSort
More file actions
66 lines (59 loc) · 1.35 KB
/
Copy pathMergeSort
File metadata and controls
66 lines (59 loc) · 1.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package sortingAndSearching;
public class MergeSort {
public static int[] merge(int[] left, int[] right, int[] array) {
int leftSize = left.length;
int rightSize = right.length;
int leftIndex = 0;
int rightIndex = 0;
int index = 0;
while (leftIndex < leftSize && rightIndex < rightSize) {
if (left[leftIndex] <= right[rightIndex]) {
array[index] = left[leftIndex];
leftIndex++;
} else {
array[index] = right[rightIndex];
rightIndex++;
}
index++;
}
while (leftIndex < leftSize) {
array[index] = left[leftIndex];
index++;
leftIndex++;
}
while (rightIndex < rightSize) {
array[index] = right[rightIndex];
index++;
rightIndex++;
}
return array;
}
public static int[] mergeSort(int[] array) {
int arraySize = array.length;
if (arraySize < 2) {
return array;
}
int mid = arraySize / 2;
int[] left = new int[mid];
int[] right = new int[arraySize - mid];
int leftIndex = 0;
int rightIndex = 0;
int index = 0;
int leftSize = left.length;
int rightSize = right.length;
while (leftIndex < leftSize) {
left[leftIndex] = array[index];
index++;
leftIndex++;
}
while (rightIndex < rightSize) {
right[rightIndex] = array[index];
index++;
rightIndex++;
}
left = mergeSort(left);
right = mergeSort(right);
array = merge(left, right, array);
return array;
}
}