-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMergeSortRecursion.java
More file actions
66 lines (46 loc) · 1.27 KB
/
MergeSortRecursion.java
File metadata and controls
66 lines (46 loc) · 1.27 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
public class solution {
public static void mergeSort(int[] a){
int n = a.length;
if(n <=1)
return;
int b[] = new int[n/2];
int c[] = new int[n - b.length];
for(int i=0; i<n/2; i++){
b[i] = a[i];
}
for(int i= n/2; i<n; i++){
c[i - n/2] = a[i];
}
mergeSort(b);
mergeSort(c);
merge(b ,c ,a);
}
public static void merge(int arr1[], int arr2[], int arr[]) {
int m = arr1.length;
int n = arr2.length;
int i =0;
int j=0;
int k=0;
while(i<m && j<n){
if(arr1[i] <= arr2[j]){
arr[k] = arr1[i];
i++;
k++;
}else{
arr[k] = arr2[j];
j++;
k++;
}
}
while(i<m){
arr[k] = arr1[i];
i++;
k++;
}
while(j<n){
arr[k] = arr2[j];
j++;
k++;
}
}
}