-
Notifications
You must be signed in to change notification settings - Fork 10
/
MergeSort.java
61 lines (53 loc) · 915 Bytes
/
MergeSort.java
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
package sorting_algo;
public class MergeSort {
public static void main(String[] args) {
int arr[] = mergeSort(new int[] {34,6,78,34,87,98,56,98,0,-76,-54,-65,999}, 0, 12);
for(int i=0; i<arr.length; i++) {
System.out.print(arr[i]+" ");
}
}
public static int[] mergeSort(int[] a, int l, int r) {
if(l<r) {
int mid = (l+r)/2;
mergeSort(a, l, mid);
mergeSort(a, mid+1, r);
merge(a, l, mid, r);
}
return a;
}
public static int[] merge(int[] a, int l, int mid, int r) {
int b[] = new int[a.length];
int i = l;
int j = mid+1;
int k = l;
while(i<=mid && j<=r) {
if(a[i]<a[j]) {
b[k]=a[i];
i++;
}
else {
b[k]=a[j];
j++;
}
k++;
}
if(i>mid) {
while(j<=r) {
b[k]=a[j];
k++;
j++;
}
}
else {
while(i<=mid) {
b[k]=a[i];
k++;
i++;
}
}
for(k=l; k<=r; k++) {
a[k]=b[k];
}
return a;
}
}