Skip to content

Commit f4c36fc

Browse files
Merge pull request matthewsamuel95#684 from nayomi16/master
Create merge_sort.java
2 parents d3a9471 + e4e5357 commit f4c36fc

File tree

1 file changed

+64
-0
lines changed

1 file changed

+64
-0
lines changed
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
public class MergerSort {
2+
3+
public static void mergeSort(Comparable[] array) {
4+
Comparable[] temp = new Comparable[array.length];
5+
mergeSort(array, temp, 0, array.length - 1);
6+
}
7+
8+
private static void merge(Comparable[] a, Comparable[] temp, int left, int right, int rightLast) {
9+
int leftLast = right - 1;
10+
int k = left;
11+
int num = rightLast - left + 1;
12+
13+
while (left <= leftLast && right <= rightLast) {
14+
if (a[left].compareTo(a[right]) <= 0) {
15+
temp[k++] = a[left++];
16+
} else {
17+
temp[k++] = a[right++];
18+
}
19+
}
20+
21+
while (left <= leftLast) // The rest of the first half will be copied
22+
{
23+
temp[k++] = a[left++];
24+
}
25+
26+
while (right <= rightLast) // The rest of the right half will be copied
27+
{
28+
temp[k++] = a[right++];
29+
}
30+
31+
// The temp array will copied back
32+
for (int i = 0; i < num; i++, rightLast--) {
33+
a[rightLast] = temp[rightLast];
34+
}
35+
}
36+
37+
private static void mergeSort(Comparable[] arr, Comparable[] tmp, int left, int right) {
38+
if (left < right) {
39+
int center = (left + right) / 2;
40+
mergeSort(arr, tmp, left, center);
41+
mergeSort(arr, tmp, center + 1, right);
42+
merge(arr, tmp, left, center + 1, right);
43+
}
44+
}
45+
46+
public static void printArray(Integer arr[]) {
47+
int n = arr.length;
48+
for (int i = 0; i < n; ++i) {
49+
System.out.print(arr[i] + " ");
50+
}
51+
System.out.println();
52+
}
53+
54+
public static void main(String[] args) {
55+
Integer[] arr = {473, 78, 92, 5, 18, 7, 65, 89};
56+
System.out.println("Before: ");
57+
printArray(arr);
58+
59+
mergeSort(arr);
60+
61+
System.out.println("After: ");
62+
printArray(arr);
63+
}
64+
}

0 commit comments

Comments
 (0)