#include<iostream>
using namespace std;
//归并排序
int nums[155];
int tmp[155]; //辅助数组,暂时存放要归并的序列
//归并
void Merge(int* nums, int left, int mid, int right) {
for (int i = left; i <= right;i++) {
tmp[i] = nums[i]; //将要归并的序列暂时存放在 辅助数组tmp中
}
//将两个子数组合并成一个数组
int i = left, j = mid + 1, k = left;
for (k = left;i <= mid && j <= right;k++) {
if (tmp[i] <= tmp[j]) {
nums[k] = tmp[i++];
}
else {
nums[k] = tmp[j++];
}
}
while (i <= mid) nums[k++] = tmp[i++];
while (j <= right) nums[k++] = tmp[j++];
}
//归并排序
void MergeSort(int* nums, int left, int right) {
if (left >= right) //递归终止条件,只剩下一个元素时停止划分
return;
int mid = (left + right) / 2; //划分边界
MergeSort(nums, left, mid); //对左边部分进行归并排序
MergeSort(nums, mid + 1, right); //对右半部分进行归并排序
Merge(nums, left, mid, right); //归并
}
int main() {
int n;
cin >> n;
for (int i = 0;i < n;i++) {
cin >> nums[i];
}
MergeSort(nums, 0, n - 1); //归并排序
cout << "排序后的序列为:";
for (int i = 0;i < n;i++) {
cout << nums[i] << " ";
}
return 0;
}
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://blog.csdn.net/weixin_47511190/article/details/120034339
内容来源于网络,如有侵权,请联系作者删除!