Skip to content

Instantly share code, notes, and snippets.

@dmnugent80
Created February 17, 2015 04:54
Show Gist options
  • Save dmnugent80/92915b24c25079304ba0 to your computer and use it in GitHub Desktop.
Save dmnugent80/92915b24c25079304ba0 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);
mergeSort(array, helper, middle + 1, high);
merge(array, helper, low, middle, high);
}
}
void merge(int[] array, int[] helper, int low, int middle, int high){
for (int i = low; i <= high; i++){
helper[i] = helper[i];
}
int helperLeft = low;
int helperRight = middle + 1;
int current = low;
while (helperLeft <= middle && helperRight <= high){
if (helper[helperLeft] <= helper[helperRight]){
array[current] = helper[helperLeft];
helperLeft++;
}
else{
array[current] = helper[helperRight];
helperRight++;
}
current++;
}
while (helperLeft <= middle){
array[current] = helper[helperLeft];
current++;
helperLeft++;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment