Skip to content

Instantly share code, notes, and snippets.

@kingdido999
Created January 11, 2016 20:41
Show Gist options
  • Save kingdido999/311b65d89f51211088b8 to your computer and use it in GitHub Desktop.
Save kingdido999/311b65d89f51211088b8 to your computer and use it in GitHub Desktop.
Top-down implementation of merge sort.
void mergeSort(int[] a, int[] b, int first, int last) {
if (first < last) {
int mid = (first + last) / 2;
mergeSort(a, b, first, mid - 1);
mergeSort(a, b, mid, last);
merge(a, b, first, mid, last);
copyBtoA(b, a, first, last);
}
}
void merge(int[] a, int[] b, int first, int mid, int last) {
int left = first;
int right = mid;
for (int i = first; i < last; i++) {
if (i < mid && (right > last || a[left] <= a[right])) {
b[i] = a[left];
left++;
} else {
b[i] = a[right];
right++;
}
}
}
void copyBtoA(int[] b, int[] a, int first, int last) {
for (int i = first; i < last; i++) {
a[i] = b[i];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment