归并排序
程序员文章站
2022-05-10 15:36:43
...
时间复杂度(N*logN)
#include<iostream>
#include<stdio.h>
#include<vector>
using namespace std;
int a[100];
vector<int>ve;
void merge(int* x, int L, int mid, int R) {
int p1, p2;
p1 = L;
p2 = mid + 1;
while (p1 <= mid && p2 <= R) {
ve.push_back(x[p1] < x[p2] ? x[p1++] : x[p2++]);
}
while (p1 <= mid) {
ve.push_back(x[p1++]);
}
while (p2 <= R) {
ve.push_back(x[p2++]);
}
for (int i=0; i < ve.size(); i++) {//将排好序的数据拷贝到原来数组中去
x[L + i] = ve[i];
}
}
int Pai(int* arr, int L, int R) {
if (L == R)
return arr[L];
int mid = (L + R) / 2;
Pai(arr, L, mid);//将整个区间的左区间排序
Pai(arr, mid + 1, R);//有区间排序
ve.clear();
merge(arr, L, mid,R);//借助ve数组将连个区间重新排序
}
int main()
{
int n;
cout << "输入要排序的个数:";
cin >> n;
cout << "输入要排序的数,用空格隔开:";
for (int i = 0; i < n; i++)
cin>>a[i];
Pai(a, 0, n - 1);
for (int i = 0; i < n; i++)
cout << a[i] << ' ';
return 0;
}