Skip to content

Commit fa0bebc

Browse files
committed
New merge sort added
1 parent 288f684 commit fa0bebc

File tree

2 files changed

+71
-1
lines changed

2 files changed

+71
-1
lines changed

src/main/java/com/rampatra/sorting/MergeSort.java

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,9 @@
1212
public class MergeSort {
1313

1414
/**
15-
* Merge sort.
15+
* Merge sort. Note that we are creating unnecessary arrays in each recursive
16+
* call. This makes the algorithm simple but it occupies more space. Look at
17+
* {@link MergeSortSpaceOptimized} instead.
1618
* <p/>
1719
* Time complexity: O(n log n)
1820
* Space complexity: O(n) (also needs O(log n) stack space as it is recursive)
Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
package com.rampatra.sorting;
2+
3+
import java.util.Arrays;
4+
5+
/**
6+
* @author rampatra
7+
* @since 13/11/2018
8+
*/
9+
public class MergeSortSpaceOptimized {
10+
11+
/**
12+
* This is entry point. You can call this method to sort
13+
* an array {@code a}.
14+
*
15+
* @param a array to be sorted
16+
*/
17+
public static void mergeSort(int[] a) {
18+
mergeSort(a, new int[a.length], 0, a.length - 1);
19+
}
20+
21+
private static void mergeSort(int[] a, int[] helper, int low, int high) {
22+
if (low < high) {
23+
int mid = (low + high) / 2; // to prevent overflow you can instead do: mid = low + (high - low) / 2
24+
25+
mergeSort(a, helper, low, mid);
26+
mergeSort(a, helper, mid + 1, high);
27+
28+
merge(a, helper, low, mid, high);
29+
}
30+
}
31+
32+
private static void merge(int[] a, int[] helper, int low, int mid, int high) {
33+
// have a helper array from which you will choose numbers and finally place it in a
34+
for (int i = low; i <= high; i++) {
35+
helper[i] = a[i];
36+
}
37+
38+
int helperLeft = low;
39+
int helperRight = mid + 1;
40+
int current = low;
41+
42+
// check left half of the helper array with the right half
43+
while (helperLeft <= mid && helperRight <= high) {
44+
if (helper[helperLeft] < helper[helperRight]) {
45+
a[current++] = helper[helperLeft++];
46+
} else {
47+
a[current++] = helper[helperRight++];
48+
}
49+
}
50+
51+
// copy the left half of the helper array and not the right
52+
// half as the right half is already there in array a
53+
for (int i = helperLeft; i <= mid; i++) {
54+
a[current++] = helper[i];
55+
}
56+
}
57+
58+
public static void main(String[] args) {
59+
int[] a = {3, 6, 8, 9, 1, 2, 4};
60+
System.out.println(Arrays.toString(a));
61+
mergeSort(a);
62+
System.out.println(Arrays.toString(a));
63+
a = new int[]{5, 8, 1, 2, 5, 3, 0, 1, 2, 4};
64+
System.out.println(Arrays.toString(a));
65+
mergeSort(a);
66+
System.out.println(Arrays.toString(a));
67+
}
68+
}

0 commit comments

Comments
 (0)