Created
April 23, 2014 22:02
-
-
Save gabhi/11233979 to your computer and use it in GitHub Desktop.
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
<T> void mergeSort(T[] a, Comparator<T> c) { | |
if (a.length <= 1) return; | |
T[] a0 = Arrays.copyOfRange(a, 0, a.length/2); | |
T[] a1 = Arrays.copyOfRange(a, a.length/2, a.length); | |
mergeSort(a0, c); | |
mergeSort(a1, c); | |
merge(a0, a1, a, c); | |
} | |
<T> void merge(T[] a0, T[] a1, T[] a, Comparator<T> c) { | |
int i0 = 0, i1 = 0; | |
for (int i = 0; i < a.length; i++) { | |
if (i0 == a0.length) | |
a[i] = a1[i1++]; | |
else if (i1 == a1.length) | |
a[i] = a0[i0++]; | |
else if (compare(a0[i0], a1[i1]) < 0) | |
a[i] = a0[i0++]; | |
else | |
a[i] = a1[i1++]; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment