Skip to content

Instantly share code, notes, and snippets.

@jun1st
Last active January 31, 2019 08:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jun1st/bc99f8ea06bb2cbb379652355aadac00 to your computer and use it in GitHub Desktop.
Save jun1st/bc99f8ea06bb2cbb379652355aadac00 to your computer and use it in GitHub Desktop.
merge sort java version
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