快速排序
2011-12-08 22:10
99 查看
#include<iostream> using namespace std; template<class Type> void Swap(Type &x,Type &y){ Type temp = x; x = y; y = temp; } template<class Type> int Partition(Type a[],int p,int r){ int i = p,j = r + 1; Type x = a[p]; while(true){ while(a[++i] < x && i < r); while(a[--j] > x); if(i >= j) break; Swap(a[i],a[j]); } a[p] = a[j]; a[j] = x; return j; } template<class Type> void QuickSort(Type a[],int p,int r){ if(p < r){ int q = Partition(a,p,r); QuickSort(a,p,q-1); QuickSort(a,q+1,r); } } template<class Type> void Output(Type a[],int n){//输出数组 for(int i = 0;i < n;i++) cout<<a[i]<<" "; } void main(){ int a[7] = {49,38,65,97,76,13,27}; cout<<"原数组为"<<endl; Output(a,7); cout<<endl<<"数组排序后为"; QuickSort(a,0,6); cout<<endl; Output(a,7); cout<<endl; }
相关文章推荐