C排序算法
Posted 彭祥.
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C排序算法相关的知识,希望对你有一定的参考价值。
快速排序算法
#include <algorithm>
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int a[100005];
void quick_sort(int l,int r)
if(l>=r)
return;
int p1=l,p2=r;
swap(a[l],a[rand()%(r-l+1)+l]);
int pivot=a[l];
while(p1<p2)
while(a[p2]>=pivot&&p1<p2)
p2--;
while(a[p1]<=pivot&&p1<p2)
p1++;
if(p1<p2)
swap(a[p1],a[p2]);
swap(a[l],a[p1]);
quick_sort(l,p1-1);
quick_sort(p1+1,r);
int main()
srand(time(NULL));
int n;
cin >> n;
for (int i = 0; i < n; i++)
cin >> a[i];
quick_sort(0,n-1);
for (int i = 0; i < n; i++)
cout << a[i] << " ";
return 0;
冒泡排序
#include <algorithm>
#include <iostream>
using namespace std;
int a[1005];
int main()
freopen("gravity.in","r",stdin);
freopen("gravity.out","w",stdout);
int n;
cin >> n;
for (int i = 0; i < n; i++)
cin >> a[i];
for(int i=0;i<n-1;i++)
bool swapped=false;
for(int j=0;j<n-i-1;j++)
if(a[j]>a[j+1])
swap(a[j],a[j+1]);
swapped=true;
if(!swapped)
break;
for (int i = 0; i < n; i++)
cout << a[i] << " ";
return 0;
插入排序
#include <iostream>
#include <algorithm>
using namespace std;
int a[1005];
int main()
int n;
cin >> n;
for (int i = 0; i < n; i++)
cin >> a[i];
for(int i=0;i<n;i++)
for(int j=i;j>=1;j--)
if(a[j]<a[j-1])
swap(a[j],a[j-1]);
else
break;
for (int i = 0; i < n; i++)
cout << a[i] << " ";
return 0;
选择排序
#include <algorithm>
#include <iostream>
using namespace std;
int a[1005];
int main()
int n;
cin >> n;
for (int i = 0; i < n; i++)
cin >> a[i];
for(int i=0;i<n-1;i++)
int min_id=i;
for(int j=i+1;j<n;j++)
if(a[j]<a[min_id])
min_id=j;
if(i!=min_id)
swap(a[i],a[min_id]);
for (int i = 0; i < n; i++)
cout << a[i] << " ";
return 0;
归并排序
#include <iostream>
using namespace std;
int a[100005], b[100005];
void merge(int l, int r)
int p1=l,mid=(l+r)/2,p2=mid+1,p=l;
while(p1<=mid&&p2<=r)
if(a[p1]<=a[p2])
b[p++]=a[p1++];
else
b[p++]=a[p2++];
while(p1<=mid)
b[p++]=a[p1++];
while(p2<=r)
b[p++]=a[p2++];
for(int i=l;i<=r;i++)
a[i]=b[i];
void merge_sort(int l, int r)
if(l==r)
return;
int mid=(l+r)/2;
merge_sort(l,mid);
merge_sort(mid+1,r);
merge(l,r);
int main()
int n;
cin >> n;
for (int i = 0; i < n; i++)
cin >> a[i];
merge_sort(0,n-1);
for (int i = 0; i < n; i++)
cout << a[i] << " ";
return 0;
以上是关于C排序算法的主要内容,如果未能解决你的问题,请参考以下文章