Skip to content

Commit 14236bb

Browse files
committedAug 26, 2019
implement merge sort version of premaseem
1 parent df439f7 commit 14236bb

File tree

3 files changed

+56
-92
lines changed

3 files changed

+56
-92
lines changed
 

‎src/me/premaseem/algorithm/mergesort/App.java

Lines changed: 0 additions & 67 deletions
This file was deleted.
Lines changed: 56 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,73 @@
11
package me.premaseem.algorithm.mergesort;
22

3-
import org.junit.Assert;
3+
/*
4+
Implement merge sort
5+
*/
6+
7+
import me.premaseem.MyUtils;
48
import org.junit.Test;
59

610
public class MergeSort {
711

812
// Test Driven Development by Aseem Jain
913
@Test
1014
public void test() {
15+
int a2[] = {10, 30, 190, 120, 110, 50, 7};
16+
17+
mergeSort(a2, 0, a2.length - 1);
18+
MyUtils.isArrSorted(a2);
19+
}
1120

12-
int a1[] = {40, 20, 50, 100, 40, 80};
13-
int a2[] = {10, 30, 90, 70, 40 };
1421

22+
void mergeSort(int[] a, int l, int r) {
23+
if (r > l) {
24+
int m = (l + r) / 2;
25+
mergeSort(a,l,m);
26+
mergeSort(a,m+1,r);
27+
realMerge(a, l, m, r);
28+
}
1529
}
1630

31+
void realMerge(int[] a, int l, int m, int r) {
32+
33+
// find out array size
34+
int las = m - l + 1; // add one because of zero index
35+
int ras = r - m;
36+
int[] la = new int[las];
37+
int[] ra = new int[ras];
38+
39+
// populate elements
1740

18-
public void sort(int[] a){
41+
for (int i = 0; i < las; i++) {
42+
la[i] = a[l + i];
43+
}
1944

45+
for (int i = 0; i < ras; i++) {
46+
ra[i] = a[m + 1 + i]; // since m is covered in last loop, add m+1 here
47+
}
48+
49+
// merge and put it on real array
50+
int i1 = 0, i2 = 0;
51+
52+
for (int i = l; i <= r; i++) {
53+
int lav = Integer.MAX_VALUE;
54+
int rav = Integer.MAX_VALUE;
55+
56+
if (i1 < las) {
57+
lav = la[i1];
58+
}
59+
if (i2 < ras) {
60+
rav = ra[i2];
61+
}
62+
63+
if (lav < rav) {
64+
a[i] = lav;
65+
i1++;
66+
} else {
67+
a[i] = rav;
68+
i2++;
69+
}
70+
}
2071
}
72+
2173
}

‎src/me/premaseem/algorithm/mergesort/Test.java

Lines changed: 0 additions & 21 deletions
This file was deleted.

0 commit comments

Comments
 (0)