之前都只是听过这些排序的名字,但因为感觉用不上就没学,今天看了一下,感觉看讲解还没直接看代码理解快,大概是看几分钟就能自己实现的程度。。
#include <bits/stdc++.h>
#define ll long long
using namespace std;
const int N = 505;
int a[N], b[N];
void mergesort(int l, int mid, int r){
int p1 = l, p2 = mid+1, pos = l;
while(p1<=mid && p2<=r){
if(a[p1] <= a[p2]){
b[pos++] = a[p1++];
} else {
b[pos++] = a[p2++];
}
}
while(p1<=mid) b[pos++] = a[p1++];
while(p2<=r) b[pos++] = a[p2++];
for(int i = l;i <= r;i++){
a[i] = b[i];
}
}
void split(int l, int r){
if(l >= r) return;
int mid = l+r>>1;
split(l, mid);
split(mid+1, r);
mergesort(l, mid, r);
}
int main(){
int n;
cin>>n;
for(int i = 1;i <= n;i++){
cin>>a[i];
}
split(1, n);
for(int i = 1;i <= n;i++){
printf("%d ", a[i]);
}
return 0;
}
快排
#include <bits/stdc++.h>
#define ll long long
using namespace std;
const int N = 505;
int a[N];
int qksort(int l ,int r){
int res = a[l];
while(l < r){
while(l<r && a[r]>=res) r--;
a[l] = a[r];
while(l<r && a[l]<=res) l++;
a[r] = a[l];
}
a[l] = res;
return l;
}
void solve(int l, int r){
if(l < r){
int pos = qksort(l, r);
solve(l, pos-1);
solve(pos+1, r);
}
}
int main(){
int n;
cin>>n;
for(int i = 1;i <= n;i++){
cin>>a[i];
}
solve(1, n);
for(int i = 1;i <= n;i++){
printf("%d ", a[i]);
}
return 0;
}