递归
private void mergeSort(int[] nums, final int L, final int R) {
if (L == R) {
return;
}
final int M = L + (R - L) / 2;
mergeSort(nums, L, M);
mergeSort(nums, M + 1, R);
merge(nums, L, M, R);
}
合并两个有序数组
private void merge(int[] nums, final int L, final int M, final int R) {
int[] tmp = new int[R - L + 1];
int l = L, r = M + 1, p = 0;
while (l <= M && r <= R) {
tmp[p++] = nums[l] < nums[r] ? nums[l++] : nums[r++];
}
while (l <= M) {
tmp[p++] = nums[l++];
}
while (r <= R) {
tmp[p++] = nums[r++];
}
System.arraycopy(tmp, 0, nums, L, tmp.length);
}
多线程
private void concurrentMergeSort(int[] nums, final int L, final int R) {
if (L == R) {
return;
}
final int M = L + (R - L) / 2;
Thread leftSort = new Thread(() -> mergeSort(nums, L, M));
Thread rightSort = new Thread(() -> mergeSort(nums, M + 1, R));
leftSort.start();
rightSort.start();
try {
leftSort.join();
rightSort.join();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
merge(nums, L, M, R);
}
自定义线程数多线程
private void customConcurrentMergeSort(int[] nums, final int L, final int R, int threadNumber) {
if (L == R) {
return;
}
final int M = L + (R - L) / 2;
Thread leftSort = new Thread(() -> {
if (threadNumber / 2 == 1) {
mergeSort(nums, L, M);
} else {
customConcurrentMergeSort(nums, L, M, threadNumber - 1);
}
});
Thread rightSort = new Thread(() -> {
if (threadNumber / 2 == 1) {
mergeSort(nums, M + 1, R);
} else {
customConcurrentMergeSort(nums, M + 1, R, threadNumber - 1);
}
});
leftSort.start();
rightSort.start();
try {
leftSort.join();
rightSort.join();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
merge(nums, L, M, R);
}
迭代
private void mergeSortIteration(int[] nums) {
if (nums == null || nums.length < 2) {
return;
}
final int N = nums.length;
int sortSize = 1;
while (sortSize < N) {
int L = 0;
while (L < N) {
final int M = L + sortSize - 1;
if (M >= N) {
break;
}
final int R = Math.min(M + sortSize, N - 1);
merge(nums, L, M, R);
L = R + 1;
}
if (sortSize > N / 2) {
break;
}
sortSize <<= 1;
}
}