選擇,冒泡,快排

閒來無事,複習了下選擇排序,冒泡排序,快速排序,與大家共享

//冒泡-----這是有問題的冒泡排序,汗,提醒自己

int main()
{
int a[N];
int i,j,t;
cout<<"input the number will be sort:"<<endl;
for(i=0;i<N;i++)
cin>>a[i];


for(i=0;i<N-1;i++)
for(j=0;j<N-1;j++)
if(a[j]>a[j+1])
{
t=a[j];
a[j]=a[j+1];
a[j+1]=t;
}
cout<<"sorted:"<<endl;
for(i=0;i<N;i++)
cout<<a[i]<<" ";
cout<<endl;
system("pause");
return 0;
}

//選擇排序

int main()
{
int a[N];
int i,j,t;
cout<<"input the number will be sort:"<<endl;
for(i=0;i<N;i++)
cin>>a[i];
for(i=0;i<N-1;i++)
for(j=i+1;j<N;j++)
if(a[i]>a[j])
{
t=a[i];
a[i]=a[j];
a[j]=t;
}
for(i=0;i<N;i++)
cout<<a[i]<<" ";
cout<<endl;
system("pause");
return 0;
}

//快排

void quicksort(int a[],int low,int high)
{
int mid;
if(low<high)
{
mid=partition(a,low,high);
quicksort(a,low,mid-1);
quicksort(a,mid+1,high);
}
}
int partition(int a[],int low,int high)
{
int temp=a[low];
while(low<high)
{
while((low<high)&&(a[high]>temp))
high--;
if(low<high)
a[low++]=a[high];
while((low<high)&&(a[low]<temp))
low++;
if(low<high)
a[high--]=a[low];
}
a[low]=temp;
return low;
}
int main()
{
int a[N];
int i;
for(i=0;i<N;i++)
cin>>a[i];
quicksort(a,0,N-1);
for(i=0;i<N;i++)
cout<<a[i]<<" ";
cout<<endl;
system("pause");
return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章