Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 59 additions & 0 deletions MergeSort.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
/*
* Mergesort impl in Java.
* Input: An array over integers that has to be sorted
* Output: Sorted Array over integers
*/

public class MergeSort {

public static void mergeSort(int[] arrToSort, int n) {

if (n < 2) {
return;
}

// Find the middle point to divide the array into two halves
int mid = n / 2;

// Divide the payload
int[] left = new int[mid];
int[] right = new int[n - mid];

for (int i = 0; i < mid; i++) {
left[i] = arrToSort[i];
}

for (int i = mid; i < n; i++) {
right[i - mid] = arrToSort[i];
}

// Call mergeSort for first half
mergeSort(left, mid);
// Call mergeSort for second half
mergeSort(right, n - mid);
// Merge the two halves sorted
merge(arrToSort, left, right, mid, n - mid);
}

public static void merge(int[] arrToSort, int[] left, int[] right, int lbound, int rbound) {

int i = 0, j = 0, k = 0;

while (i < lbound && j < rbound) {
if (left[i] <= right[j]) {
arrToSort[k++] = left[i++];
}
else {
arrToSort[k++] = right[j++];
}
}

while (i < lbound) {
arrToSort[k++] = left[i++];
}

while (j < rbound) {
arrToSort[k++] = right[j++];
}
}
}
17 changes: 17 additions & 0 deletions MergeSortTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import org.junit.Test;

import java.util.Arrays;

import static org.junit.Assert.assertArrayEquals;

public class MergeSortTest {
@Test
public void should_evaluate_to_true() {
int[] actual = { 5, 1, 6, 2, 3, 4 };
int[] expected = { 1, 2, 3, 4, 5, 6 };
System.out.println("Array before applying mergesort: " + Arrays.toString(actual));
MergeSort.mergeSort(actual, actual.length);
System.out.println("Array after applying mergesort: " + Arrays.toString(actual));
assertArrayEquals(expected, actual);
}
}