归并排序是将几个有序表归并为一个新的有序表,初始时可以看作(n)个有序子表,2路归并排序将其合并为(n/2)个有序子表:
void Merge(vector<int>& num, int low, int mid, int high) {
vector<int> tmp(high - low + 1);
int i = low; // 左有序开始位置
int j = mid + 1; // 右有序开始位置
int k = 0;
while (i <= mid && j <= high) {
if (num[i] < num[j]) {
tmp[k++] = num[i++];
}
else {
tmp[k++] = num[j++];
}
}
while (i <= mid)
tmp[k++] = num[i++];
while (j <= high)
tmp[k++] = num[j++];
for (i = 0; i < k; ++i) {
num[low + i] = tmp[i];
}
}
void mergeSort(vector<int>& num, int low, int high) {
if (low >= high)
return;
int mid = (low + high) >> 1;
mergeSort(num, low, mid);
mergeSort(num, mid + 1, high);
Merge(num, low, mid, high);
}
性能:需要辅助数组,空间复杂度(O(n));
每一趟归并(O(n)),需要(O(logn))趟归并,故时间复杂度(O(nlogn))。