归并排序代码实现与详解
归并排序介绍:
归并排序(MERGE-SORT)是利用归并的思想实现的排序方法,该算法采用经典的分治策略(分治法将问题分成一些小的问题然后递归求解,而治的阶段则将分的阶段得到的各答案"修补"在一起,即分而治之)。
代码实现(java)
// 合
private static void merge(int[] nums, int left, int mid, int right) {
int l1 = mid + 1;
int[] tmp = new int[nums.length];
int tmpindex = left;
int realindex = left;
while (left <= mid && l1 <= right) {
if (nums[left] <= nums[l1]) {
tmp[tmpindex++] = nums[left++];
} else {
tmp[tmpindex++] = nums[l1++];
}
}
while (left <= mid) {
tmp[tmpindex++] = nums[left++];
}
while (l1 <= right) {
tmp[tmpindex++] = nums[l1++];
}
while (realindex <= right) {
nums[realindex] = tmp[realindex];
realindex++;
}
}
// 分
private static void sort(int[] nums, int left, int right) {
if (left >= right) {
return;
}
int mid = (left + right) / 2;
sort(nums, left, mid);
sort(nums, mid + 1, right);
merge(nums, left, mid, right);
}