Last active
January 31, 2019 08:41
-
-
Save jun1st/bc99f8ea06bb2cbb379652355aadac00 to your computer and use it in GitHub Desktop.
merge sort java version
This file contains hidden or 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
public static void merge(int[] arrayOne, int aLeft, int aRight, | |
int[] arrayTwo, int bLeft, int bRight, | |
int[] result) { | |
int i = aLeft, j = bLeft; | |
for(int k = 0; k <= aRight - aLeft + bRight - bLeft + 1; k++) { | |
if (i > aRight) { //第一个数组没有元素了 | |
result[k] = arrayTwo[j++]; | |
continue; | |
} | |
if (j > bRight) { //第二个数组没有元素了 | |
result[k] = arrayOne[i++]; | |
continue; | |
} | |
// 把小的先插入到结果数组中 | |
result[k] = (arrayOne[i] < arrayTwo[j]) ? arrayOne[i++] : arrayTwo[j++]; | |
} | |
} | |
public static void mergeSort(int[] A, int al, int ar) { | |
if (ar > al) { | |
int middle = (ar + al) / 2; | |
mergeSort(A, al, middle); | |
mergeSort(A, middle+1, ar); | |
int[] B = new int[ar - al + 1]; | |
merge(A, al, middle, A, middle + 1, ar, B); | |
for(int i=0; i < ar - al + 1; i++) { | |
A[al + i] = B[i]; | |
} | |
System.out.println(A); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment