-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdo_MergeSort.java
More file actions
64 lines (55 loc) · 1.46 KB
/
do_MergeSort.java
File metadata and controls
64 lines (55 loc) · 1.46 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
Static int[] do_mergeSort(int[] lst) {
int n = lst.length;
int[] left;
int[] right;
// create space for left and right subarrays
if (n % 2 == 0) {
left = new int[n/2];
right = new int[n/2];
}
else {
left = new int[n/2];
right = new int[n/2+1];
}
// fill up left and right subarrays
for (int i = 0; i < n; i++) {
if (i < n/2) {
left[i] = lst[i];
}
else {
right[i-n/2] = lst[i];
}
}
// recursively split and merge
left = do_mergeSort(left);
right = do_mergeSort(right);
// merge
return merge(left, right);
}
// the function for merging two sorted arrays
static int[] merge(int[] left, int[] right) {
// create space for the merged array
int[] result = new int[left.length+right.length];
// running indices
int i = 0;
int j = 0;
int index = 0;
// add until one subarray is deplete
while (i < left.length && j < right.length) {
if (left[i] < right[j]) {
result[index++] = left[i++];
{
else {
result[index++] = right[j++];
}
}
// add every leftover elelment from the subarray
while (i < left.length) {
result[index++] = left[i++];
}
// only one of these two while loops will be executed
while (j < right.length) {
result[index++] = right[j++];
}
return result;
}