归并排序的c++实现
时间: 2024-08-12 10:00:41 浏览: 96
归并排序是一种基于分治策略的高效排序算法。它的基本思想是将数组不断二分,然后对每一半进行排序,最后合并两个有序部分。以下是C++实现归并排序的一个简单版本:
```cpp
#include <vector>
using namespace std;
void merge(vector<int>& nums, int left, int mid, int right) {
int n1 = mid - left + 1;
int n2 = right - mid;
vector<int> L(n1), R(n2);
for (int i = 0; i < n1; i++)
L[i] = nums[left + i];
for (int j = 0; j < n2; j++)
R[j] = nums[mid + 1 + j];
int i = 0, j = 0, k = left;
while (i < n1 && j < n2) {
if (L[i] <= R[j])
nums[k++] = L[i++];
else
nums[k++] = R[j++];
}
// 将剩余未处理的部分直接复制到结果数组
while (i < n1)
nums[k++] = L[i++];
while (j < n2)
nums[k++] = R[j++];
}
void mergeSort(vector<int>& nums, int left, int right) {
if (left < right) {
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 = {4, 1, 3, 2, 6, 5};
int size = nums.size();
mergeSort(nums, 0, size - 1);
for (int num : nums)
cout << num << " ";
return 0;
}
```
阅读全文