Skip to content

Commit ee82980

Browse files
Create merge sort
1 parent 75006ed commit ee82980

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed

merge sort

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
// "static void main" must be defined in a public class.
2+
public class Main {
3+
public static void main(String[] args) {
4+
int[] arr = {2, 1, 3, 1, 2};
5+
count = 0;
6+
int[] res = mergeSort(arr, 0, arr.length-1);
7+
System.out.println(count);
8+
System.out.println(Arrays.toString(res));
9+
}
10+
static int count;
11+
static int[] mergeSort(int[] arr, int lo, int hi){
12+
if(lo == hi){
13+
// int[] bs = new int[1];
14+
// bs[0] = arr[lo];
15+
// return bs;
16+
return new int[]{arr[lo]};
17+
}
18+
// if(lo < hi){
19+
int mid = (lo + hi)/2;
20+
int[] left = mergeSort(arr, lo, mid);
21+
int[] right = mergeSort(arr, mid+1, hi);
22+
23+
int[] res = mergeTwoSortedArray(left, right);
24+
return res;
25+
// }else {
26+
// return new int[]{arr[lo]};
27+
// }
28+
29+
}
30+
// cnt = 1
31+
// {2, 1, 3, 1, 2};
32+
// 1 2 3 1 2
33+
//
34+
//
35+
static int[] mergeTwoSortedArray(int[] left, int[] right){
36+
int n = left.length;
37+
int m = right.length;
38+
39+
// 1 2 3 5
40+
// 2 2 4
41+
42+
// 1 2 2 2 4 5
43+
44+
45+
int[] res = new int[n+m];
46+
int i = 0;
47+
int j = 0;
48+
int k = 0;
49+
while(i<n && j<m){
50+
if(left[i]<=right[j]){
51+
res[k++] = left[i++];
52+
}else {
53+
count += n - i;
54+
res[k++] = right[j++];
55+
}
56+
}
57+
58+
while(i<n){
59+
res[k++] = left[i++];
60+
}
61+
while(j<m){
62+
res[k++] = right[j++];
63+
}
64+
return res;
65+
}
66+
}
67+
68+
69+
70+
71+
72+

0 commit comments

Comments
 (0)