-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMergeSort.java
More file actions
60 lines (50 loc) · 1.34 KB
/
MergeSort.java
File metadata and controls
60 lines (50 loc) · 1.34 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
public class MergeSort {
public static void Merge(int arr[], int s, int mid, int e) {
int merge[] = new int[e - s + 1];
int idx1 = s;
int idx2 = mid + 1;
int x = 0;
while (idx1 <= mid && idx2 <= e) {
if (arr[idx1] <= arr[idx2]) {
merge[x] = arr[idx1];
x++;
idx1++;
} else {
merge[x] = arr[idx2];
x++;
idx2++;
}
}
while (idx1 <= mid) {
merge[x] = arr[idx1];
x++;
idx1++;
}
while (idx2 <= e) {
merge[x] = arr[idx2];
x++;
idx2++;
}
for(int i=0,j = s;i < merge.length;i++,j++){
arr[j] = merge[i];
}
}
public static void divide(int arr[], int s, int e) {
if (s >= e) {
return;
}
int mid = s + (e - s) / 2; // (s + e)/2; is way to find mid
divide(arr, s, mid);
divide(arr, mid + 1, e);
Merge(arr, s, mid, e);
}
public static void main(String[] args) {
int arr[] = {6,3,9,5,2,8};
int n = arr.length;
divide(arr, 0, n-1);
for(int i=0; i<n; i++){
System.out.print(arr[i]+" ");
}
System.out.println();
}
}