-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmerge sort
72 lines (59 loc) · 1.63 KB
/
merge sort
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
// "static void main" must be defined in a public class.
public class Main {
public static void main(String[] args) {
int[] arr = {2, 1, 3, 1, 2};
count = 0;
int[] res = mergeSort(arr, 0, arr.length-1);
System.out.println(count);
System.out.println(Arrays.toString(res));
}
static int count;
static int[] mergeSort(int[] arr, int lo, int hi){
if(lo == hi){
// int[] bs = new int[1];
// bs[0] = arr[lo];
// return bs;
return new int[]{arr[lo]};
}
// if(lo < hi){
int mid = (lo + hi)/2;
int[] left = mergeSort(arr, lo, mid);
int[] right = mergeSort(arr, mid+1, hi);
int[] res = mergeTwoSortedArray(left, right);
return res;
// }else {
// return new int[]{arr[lo]};
// }
}
// cnt = 1
// {2, 1, 3, 1, 2};
// 1 2 3 1 2
//
//
static int[] mergeTwoSortedArray(int[] left, int[] right){
int n = left.length;
int m = right.length;
// 1 2 3 5
// 2 2 4
// 1 2 2 2 4 5
int[] res = new int[n+m];
int i = 0;
int j = 0;
int k = 0;
while(i<n && j<m){
if(left[i]<=right[j]){
res[k++] = left[i++];
}else {
count += n - i;
res[k++] = right[j++];
}
}
while(i<n){
res[k++] = left[i++];
}
while(j<m){
res[k++] = right[j++];
}
return res;
}
}