冒泡排序,选择排序,快速排序,插入排序,折半选择排序

来源:互联网 发布:大学生就业形势 知乎 编辑:程序博客网 时间:2024/06/08 06:16
#include<iostream>#define MAX 1000using namespace std;//简单插入排序void InsertSort(int a[],int len){for(int i=1;i<len;i++){int j;int temp;for(j=i-1;(j>=0)&&(a[j]>a[i]);j--);temp=a[i];for(int k=i-1;k>j;k--)a[k+1]=a[k];a[j+1]=temp;}for(int i=0;i<len;i++)cout<<a[i]<<" ";cout<<endl;}//折半插入排序void BInsertSort(int a[],int len){for(int i=1;i<len;i++){int low=0;int high=i-1;int m;while(low<=high){m=(low+high)/2;if(a[m]>a[i])high=m-1;elselow=m+1;}int temp=a[i];for(int k=i-1;k>high;k--)a[k+1]=a[k];a[high+1]=temp;}for(int i=0;i<len;i++)cout<<a[i]<<" ";cout<<endl;}//冒泡排序void BubbleSort(int a[],int len){for(int i=0;i<len;i++){int flag=false;for(int j=0;j<len-1-i;j++)if(a[j]>a[j+1]){int temp;temp=a[j];a[j]=a[j+1];a[j+1]=temp;flag=true;}if(!flag)break;}for(int i=0;i<len;i++)cout<<a[i]<<" ";cout<<endl;}//快速排序void QuickSort(int a[],int low,int high){if(low>=high)return;int l=low;int r=high;int m=a[(low+high)/2];while(l<r){while(a[l]<m)l++;while(m<a[r])r--;if(l<=r){int temp;temp=a[l];a[l]=a[r];a[r]=temp;l++;r--;}}if(l<high)QuickSort(a,l,high);if(r>low)QuickSort(a,low,r);}//选择排序void SelectSort(int a[],int len){for(int i=0;i<len;i++){int minIndex=i;for(int j=i+1;j<len;j++){if(a[j]<a[minIndex])minIndex=j;}if(i!=minIndex){int temp;temp=a[i];a[i]=a[minIndex];a[minIndex]=temp;}}}void main(){while(true){int a[MAX];cout<<"请输入待排序的数组的长度:"<<endl;int len;cin>>len;cout<<"请输入数据:"<<endl;for(int i=0;i<len;i++)cin>>a[i];/*InsertSort(a,len);*//*BInsertSort(a,len);*//*BubbleSort(a,len);*//*QuickSort(a,0,len-1);*/SelectSort(a,len);for(int i=0;i<len;i++)cout<<a[i]<<" ";cout<<endl;}}

原创粉丝点击