Skip to content

Instantly share code, notes, and snippets.

@danielrobertson
Created July 10, 2016 23:15
Show Gist options
  • Save danielrobertson/113222df71a4db85c1b40371b9030975 to your computer and use it in GitHub Desktop.
Save danielrobertson/113222df71a4db85c1b40371b9030975 to your computer and use it in GitHub Desktop.
Merge Sort
void mergesort(int[] array) {
int[] helper = new int[array.length];
mergesort(array, helper, 0, array.length - 1);
}
void mergesort(int[] array, int[] helper, int low, int high) {
if (low < high) {
int middle = (low + high) / 2;
mergesort(array, helper, low, middle); // left
mergesort(array, helper, middle + 1, high); // right
merge(array, helper, low, middle, high);
}
}
void merge(int[] array, int[] helper, int low, int middle, int high) {
//We can only store first half of the array if we want.
for (int i = low; i <= high; i++) {
helper[i] = array[i];
}
int helperLeft = low;
int helperRight = middle + 1;
int current = low;
while (helperLeft <= middle && helperRight <= high) {
array[current++] = helper[helperLeft] < helper[helperRight]
? helper[helperLeft++]
: helper[helperRight++];
}
while (helperLeft <= middle) {
array[current++] = helper[helperLeft++];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment