快排--不一樣的partition函式
阿新 • • 發佈:2019-01-05
#include <iostream> using namespace std; int partitions(int a[],int start,int endindex) { if(start>=endindex) return -1; int small = start-1;//small是所有比目標數字都小的最大索引 int index; for(index= start;index<endindex;index++) { if(a[index]<a[endindex]) { small++; if(small!=index) { int tmp = a[small]; a[small] = a[index]; a[index] = tmp; } } } small++; int tmp = a[small]; a[small] = a[endindex]; a[endindex] = tmp; return small; } void quicksort(int a[],int start,int endindex) { if(start>=endindex) return; int index = partitions(a,start,endindex); if(index==-1) return; quicksort(a,start,index-1); quicksort(a,index+1,endindex); } int main() { for(;;) { int a[5]; for(int i=0;i<5;i++) cin>>a[i]; quicksort(a,0,4); for(int i=0;i<5;i++) cout<<a[i]<<' '; cout<<endl; } return 0; }