Created
January 11, 2016 20:41
-
-
Save kingdido999/311b65d89f51211088b8 to your computer and use it in GitHub Desktop.
Top-down implementation of merge sort.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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