用 c++实现归并排序
时间: 2023-07-11 12:50:27 浏览: 93
好的,以下是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 = {5, 2, 6, 1, 3, 9, 4, 8, 7};
mergeSort(nums, 0, nums.size() - 1);
for (int num : nums) {
cout << num << " ";
}
return 0;
}
```
归并排序的核心思想是分治,将一个大问题分成两个小问题,分别解决,最后将两个小问题的解合并起来,就得到了大问题的解。具体实现时,先将数组从中间分成左右两部分,然后递归地对左右两部分进行排序,最后将排序后的左右两部分合并起来。时间复杂度为O(nlogn)。
阅读全文