两路合并排序算法c++
时间: 2023-08-04 18:10:30 浏览: 127
C语言二路归并排序算法
下面是一个简单的 C++ 实现合并排序算法的代码:
```c++
#include <iostream>
#include <vector>
using namespace std;
void merge(vector<int>& nums, int left, int mid, int right) {
vector<int> temp(right - left + 1);
int i = left, j = mid + 1, k = 0;
while (i <= mid && j <= right) {
if (nums[i] <= nums[j]) {
temp[k++] = nums[i++];
} else {
temp[k++] = nums[j++];
}
}
while (i <= mid) {
temp[k++] = nums[i++];
}
while (j <= right) {
temp[k++] = nums[j++];
}
for (int p = 0; p < temp.size(); p++) {
nums[left + p] = temp[p];
}
}
void mergeSort(vector<int>& nums, int left, int right) {
if (left >= right) return;
int mid = left + (right - left) / 2;
mergeSort(nums, left, mid);
mergeSort(nums, mid + 1, right);
merge(nums, left, mid, right);
}
int main() {
vector<int> nums = {9, 7, 8, 3, 2, 1, 5, 4, 6};
mergeSort(nums, 0, nums.size() - 1);
for (int num : nums) {
cout << num << " ";
}
cout << endl;
return 0;
}
```
该算法时间复杂度为 $O(n \log n)$,其中 $n$ 为待排序数组的长度。
阅读全文