荷兰国旗问题
#include<iostream>
#include<cstdio>
using namespace std;
int main()
{
int a[10]={1,8,5,2,0,9,6,44,8,3};
int num;
while(cin>>num)
{
int left=-1;
int right=10;
int index=0;
while(index<right)
{
if(a[index]<num)
swap(a[++left],a[index++]);
else if(a[index]>num)
swap(a[--right],a[index]);
else
index++;
}
for(int i=0;i<10;i++)
printf("%d ",a[i]);
printf("\n");
}
return 0;
}
快速排序
经典快排
(与数据状况有关,当原数组已经按照从小到大或从大到小排列好了,这经典快排的时间复杂度为O(N^2),这是经典快排的缺点)
//快速排序(从小到大)
#include<iostream>
#include<cstdio>
using namespace std;
int n;
int l;
void quick_sort(int *p,int L,int R)
{
if(L<R)
{
int left=L-1;
int x=L-1;
int right=R;
while(L<right)
{
if(p[L]<p[R])
swap(p[++left],p[L++]);
else if(p[L]>p[R])
swap(p[--right],p[L]);
else
L++;
}
swap(p[right],p[R]);
if(left==x)//当left==x时,说明最左端的部分没变,且最左端的为当前排序中的最小值,则下次排序就不需要对l位置的数进行排序;
l++;
quick_sort(p,l,left);//也可写成quick_sort(p,0,left),就是时间复杂度中的常数部分多了,也无伤大雅;
quick_sort(p,right+1,R);
}
}
int main()
{
while(cin>>n)
{
int a[100];
l=0;
for(int i=0;i<n;i++)
cin>>a[i];
quick_sort(a,0,n-1);
for(int i=0;i<n;i++)
cout<<a[i]<<' ';
cout<<'\n';
}
return 0;
}
随机快排
其时间复杂度为O(n*log(n));
#include<iostream>
#include<cstdio>
#include<ctime>
#include<cstdlib>
using namespace std;
int l;
double random(double start,double finish)//随机数产生器,其范围为[start,finish];
{
return start+(finish-start)*rand()/(RAND_MAX+1.0);
}
int quick_sort(int *p,int L,int R)
{
if(L>=R)
return 0;
srand(unsigned(time(0)));
int x=random(L,R);//x为随机产生的数;并且L<=x<=R;
swap(p[x],p[R]);
int left=L-1;
int record=L-1;
int right=R;
while(L<right)
{
if(p[L]<p[R])
swap(p[++left],p[L++]);
else if(p[L]>p[R])
swap(p[--right],p[L]);
else
L++;
}
swap(p[R],p[right]);
if(left==record)
l++;
quick_sort(p,l,left);
quick_sort(p,right+1,R);
}
int main()
{
int a[100];
int n;
while(cin>>n)
{
l=0;
for(int i=0;i<n;i++)
cin>>a[i];
quick_sort(a,0,n-1);
for(int i=0;i<n;i++)
printf("%d ",a[i]);
printf("\n");
}
return 0;
}
随机数产生器c++,借鉴大神博客
http://www.cnblogs.com/finallyliuyu/archive/2010/10/11/1848130.html