#include<iostream> using namespace std; void bubble_sort(int n,int a[]) { int i,j; for(i=n-1;i>=0;i--) { for(j=0;j<=i;j++) { if(a[j]>a[j+1]) { swap(a[j],a[j+1]); } } } } void heap_sort_child(int i,int a[],int n) { if(i<=n/2) { int small=i; if(a[i]>a[2*i+1]&&2*i+1<=n) { small=2*i+1; } if(a[small]>a[2*i+2]&&2*i+2<=n) { small=2*i+2; } if(small!=i) { swap(a[i],a[small]); heap_sort_child(small,a,n); } } } void heap_sort(int a[],int n) { int m=n/2; int i; for(i=m;i>=0;i--) { heap_sort_child(i,a,n); } } void quick_sort(int low,int high,int a[]) { int m=a[low]; int left=low,right=high; while(left<right) { while(a[right]>m&&left<right) { right--; } if(left<right) { a[left++]=a[right]; } while(a[left]<m&&left<right) { left++; } if(left<right) { a[right--]=a[left]; } } a[left]=m; if(low<high) { quick_sort(low,left-1,a); quick_sort(left+1,high,a); } } void merge(int a[],int l,int m,int r) { int i=l,j=m+1,k=0; int *pd=new int [(r-l+1)*sizeof(int)]; while(i<=m&&j<=r) { pd[k++]=a[i]>a[j]? a[i++]:a[j++]; } while(i<=m) { pd[k++]=a[i++]; } while(j<=r) { pd[k++]=a[j++]; } for(k=0,i=l;i<=r;i++,k++) { a[i]=pd[k]; } delete[] pd; } void merge_sort(int a[],int l,int r) { int m; if(l<r) { m=(r+l)>>1; merge_sort(a,l,m); merge_sort(a,m+1,r); merge(a,l,m,r); } } void insert_sort(int a[],int n) { int i,position; for(i=1;i<=n;i++) { if(a[i]<a[i-1]) { position=i-1; do { swap(a[position],a[position+1]); position--; }while(position>=0&&a[position]>a[position+1]); } } } void select_sort(int a[],int n) { int i,j=0,large,position; while(j<n) { large=a[j]; position=j; for(i=j;i<=n;i++) { if(large<a[i]) { position=i; large=a[i]; } } swap(a[j],a[position]); j++; } } int main() { int a[11]={9,8,7,6,5,4,3,2,1,0}; int i; cout<<"冒泡排序"<<endl; bubble_sort(9,a); for(i=0;i<10;i++) { cout<<a[i]<<" "; } cout<<endl; cout<<"堆排序"<<endl; heap_sort(a,9); for(i=1;i<=9;i++) { swap(a[0],a[10-i]); heap_sort_child(0,a,9-i); } for(i=0;i<10;i++) { cout<<a[i]<<" "; } cout<<endl; cout<<"快速排序"<<endl; quick_sort(0,9,a); for(i=0;i<10;i++) { cout<<a[i]<<" "; } cout<<endl; cout<<"归并排序"<<endl; merge_sort(a,0,9); for(i=0;i<10;i++) { cout<<a[i]<<" "; } cout<<endl; cout<<"插入排序"<<endl; insert_sort(a,9); for(i=0;i<10;i++) { cout<<a[i]<<" "; } cout<<endl; cout<<"选择排序"<<endl; select_sort(a,9); for(i=0;i<10;i++) { cout<<a[i]<<" "; } cout<<endl; return 0; }