Skip to content

Instantly share code, notes, and snippets.

@ehgoodenough
Last active December 17, 2015 01:19
Show Gist options
  • Save ehgoodenough/5527277 to your computer and use it in GitHub Desktop.
Save ehgoodenough/5527277 to your computer and use it in GitHub Desktop.
Although I managed to implement the recursive divide and conquer algorithm, the code generates a new array as it traverses up the stack, which is really quite wasteful. There must be a more efficient implementation that mergesorts the array all in place.
public class MergeSort
{
public static void main(String[] args)
{
int[] array = {57, 36, 13, 5, 24, 42, 68, 79};
array = sort(array);
for(int num = 0; num < array.length; num++)
{
if(num > 0) {System.out.print(", ");}
System.out.print(array[num]);
}
}
public static int[] sort(int[] array)
{
return sort(array, 0, array.length);
}
public static int[] sort(int[] array, int left, int right)
{
if(right - left == 1) {int[] atom = {array[right - 1]}; return atom;}
else if(right - left < 1) {int[] atom = {}; return atom;}
int midpoint = ((right - left) / 2) + left;
return merge(sort(array, left, midpoint), sort(array, midpoint, right));
}
public static int[] merge(int[] left, int[] right)
{
int[] array = new int[left.length + right.length];
int li = 0, ri = 0;
for(int i = 0; i < array.length; i++)
{
if(li >= left.length) {array[i] = right[ri++]; continue;}
if(ri >= right.length) {array[i] = left[li++]; continue;}
if(left[li] <= right[ri]) {array[i] = left[li++];}
else {array[i] = right[ri++];}
}
return array;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment