-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathMergeSort.java
63 lines (49 loc) · 1.3 KB
/
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
62
63
/*
* Divide & Conquer
*/
public class MergeSort {
public static void mergeSort(int array[], int si, int ei) {
if (si >= ei) { // end me true
return;
}
int mid = si + (ei - si) / 2;
mergeSort(array, si, mid);
mergeSort(array, mid + 1, ei);
merge(array, si, mid, ei);
}
public static void merge(int array[], int si, int mid, int ei) {
int temp[] = new int[ei - si + 1];
int i = si;
int j = mid + 1;
int k = 0;
while (i <= mid && j <= ei) {
if (array[i] > array[j]) {
temp[k] = array[j++];
} else {
temp[k] = array[i++];
}
k++;
}
while (i <= mid) {
temp[k++] = array[i++];
}
while (j <= ei) {
temp[k++] = array[j++];
}
for (i = 0, j = si; i < temp.length; i++, j++) {
array[j] = temp[i];
}
}
public static void main(String[] args) {
int array[] = { 9, 8, 7, 6, 5, 4, 3, 2, 1 };
mergeSort(array, 0, array.length - 1);
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
System.out.println();
}
}
/*
* Output:
* 1 2 3 4 5 6 7 8 9
*/