Skip to content

Commit 96421ca

Browse files
committed
Add Merge Sort in Java
1 parent f65bfea commit 96421ca

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

MergeSort/Java/MergeSort.java

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
package com.dev.namhoai.sort;
2+
3+
public class MergeSort {
4+
5+
public static void sort(int[] a) {
6+
int[] helper = new int[a.length];
7+
sort(a, 0, a.length - 1, helper);
8+
9+
}
10+
11+
public static void sort(int[] a, int low, int high, int[] helper) {
12+
if (low >= high) {
13+
return;
14+
}
15+
int middle = low + (high - low) / 2;
16+
sort(a, low, middle, helper);
17+
sort(a, middle + 1, high, helper);
18+
merge(a, low, middle, high, helper);
19+
}
20+
21+
public static void merge(int[] a, int low, int middle, int high, int[] helper) {
22+
for (int i = low; i <= high; i++) {
23+
helper[i] = a[i];
24+
}
25+
int i = low;
26+
int j = middle + 1;
27+
28+
for (int k = low; k <= high; k++) {
29+
if (i > middle) {
30+
a[k] = helper[j++];
31+
} else if (j > high) {
32+
a[k] = helper[i++];
33+
} else if (helper[i] <= helper[j]) {
34+
a[k] = helper[i++];
35+
} else {
36+
a[k] = helper[j++];
37+
}
38+
}
39+
}
40+
}

0 commit comments

Comments
 (0)