归并排序的思想也是分治,每一次排序开始都将数组分成两段,比较相邻两个元素的大小再和其它子段合并;合并的过程也是一样,先比较两个已经排好序的子段的元素各大小放到一个新的数组中;最后的结果就是一个排好序的数组。
// 递归
void
merge_region(int set[], int low, int middle, int height) {
int index1 = low;
int index2 = middle + 1;
int* temp = new int[height - low + 1];
int t_index = 0;
while (index1 <= middle && index2 <= height) {
if (set[index1] < set[index2])
temp[t_index++] = set[index1++];
else
temp[t_index++] = set[index2++];
}
while (index1 <= middle) temp[t_index++] = set[index1++];
while (index2 <= height) temp[t_index++] = set[index2++];
for (int i = low, t_index = 0; i <= height;)
set[i++] = temp[t_index++];
delete[] temp;
}
void
merge_sort(int set[], int start, int end) {
if (start < end) {
int middle = (start + end) / 2;
merge_sort(set, start, middle);
merge_sort(set, middle + 1, end);
merge_region(set, start, middle, end);
}
}
// 非递归
void
merge_region(int set[], int low, int middle, int height) {
int index1 = low;
int index2 = middle + 1;
int* temp = new int[height - low + 1];
int t_index = 0;
while (index1 <= middle && index2 <= height) {
if (set[index1] < set[index2])
temp[t_index++] = set[index1++];
else
temp[t_index++] = set[index2++];
}
while (index1 <= middle) temp[t_index++] = set[index1++];
while (index2 <= height) temp[t_index++] = set[index2++];
for (int i = low, t_index = 0; i <= height;)
set[i++] = temp[t_index++];
delete[] temp;
}
// 分解区间
void
merge_sort(int set[], int length) {
// 确定归并区间长度, 第一次区间有2个值排好顺序,第二次区间中就有4个值排好顺序, 直到所有的数全部排好顺序
// 1, 2, 4, 6, 8……
int region = 1;
// 区间的位置和中间位置
int start = 0;
int middle = 0;
int end = 0;
while (region < length) {
start = 0;
// 判断起始位置+区间长度是否在集合长度内
while (start + region < length) {
middle = start + region - 1;
end = middle + region;
if (end > length - 1)
end = length - 1;
merge_region(set, start, middle, end);
start = end + 1;
}
region *= 2;
}
}
归并排序的时间复杂度也是O(nlogn)。