Merge pull request #319 from hdkn235/master

添加哨兵合并数组方法
This commit is contained in:
wangzheng0822 2019-05-29 18:24:08 +08:00 committed by GitHub
commit 355020464a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -57,4 +57,40 @@ public class MergeSort {
} }
} }
/**
* 合并(哨兵)
*
* @param arr
* @param p
* @param q
* @param r
*/
private static void mergeBySentry(int[] arr, int p, int q, int r) {
int[] leftArr = new int[q - p + 2];
int[] rightArr = new int[r - q + 1];
for (int i = 0; i <= q - p; i++) {
leftArr[i] = arr[p + i];
}
// 第一个数组添加哨兵最大值
leftArr[q - p + 1] = Integer.MAX_VALUE;
for (int i = 0; i < r - q; i++) {
rightArr[i] = arr[q + 1 + i];
}
// 第二个数组添加哨兵最大值
rightArr[r-q] = Integer.MAX_VALUE;
int i = 0;
int j = 0;
int k = p;
while (k <= r) {
// 当左边数组到达哨兵值时i不再增加直到右边数组读取完剩余值同理右边数组也一样
if (leftArr[i] <= rightArr[j]) {
arr[k++] = leftArr[i++];
} else {
arr[k++] = rightArr[j++];
}
}
}
} }