快速排序实现
// Type your C++ code and click the "Run Code" button! // Your code output will be shown on the left. // Click on the "Show input" button to enter input data to be read (from stdin). #include <iostream> #include<ctime> #include<cstdlib> using namespace std; void swap( int &a, int &b) { int tmp; tmp=a; a=b; b=tmp; } int RandInRange( int start, int end ) { srand(time(NULL)); return start + rand()%(end-start+1); } int Partition( int data[],int length, int start, int end) { if( data==NULL || length<=0 || start <0 || end >= length) { cout<<"形参不合理!"<<endl; exit(0); } int index=RandInRange(start,end); swap(data[index],data[end]); int lower=start-1; for( index=start; index < end; ++index ) { if( data[index] < data[end] ) { ++lower; if(lower != index ) { swap(data[lower],data[index]); } } } ++lower; swap(data[lower],data[end]); return lower; } void qsort( int data[],int length,int start,int end ) { if(start == end) return; int index = Partition(data,length,start,end); if( index >start ) qsort(data,length,start,index-1); if( index < end ) qsort(data,length,index+1,end); } int main() { // Start typing your code here... cout << "Hello world!" << endl; int data[5]={6,7,5,3,2}; qsort(data,5,0,4); for( int i=0; i< 5;i++) { cout<<data[i]<<endl; } return 0; }