1 #include "stdafx.h" 2 #include <iostream> 3 #include<stack> 4 #include<exception> 5 using namespace std; 6 7 8 void swap(int* a ,int *b) 9 { 10 int temp = *a; 11 *a=*b; 12 *b=temp; 13 } 14 int Partition(int data[],int length,int start,int end) 15 { 16 if(data==NULL||length<=0||start<0||end>=length) 17 throw new std::exception("Invalid Parameters"); 18 int index = start; 19 swap(&data[index],&data[end]); 20 int small = start-1;//small用来记录比枢轴小的数的位置. 21 for(index=start;index<end;++index) 22 { 23 if(data[index]<data[end]) 24 { 25 ++small;//找到一个比枢轴小的数就+1, 26 if(small!=index) 27 swap(&data[index],&data[small]); 28 } 29 } 30 ++small; 31 swap(&data[small],&data[end]); 32 return small; 33 } 34 void QuickSort(int data[],int length,int start,int end) 35 { 36 if(start==end) 37 return; 38 int index = Partition(data,length,start,end); 39 if(index>start) 40 QuickSort(data,length,start,index-1); 41 if(index<end) 42 QuickSort(data,length,index+1,end); 43 } 44 const int num = 6; 45 int _tmain(int argc, _TCHAR* argv[]) 46 { 47 int data[num]={4,3,1,6,10,2}; 48 QuickSort(data,num,0,num-1); 49 50 cout<<"最后结果:"<<endl; 51 for(int i = 0;i!=num-1;++i) 52 cout<<data[i]<<"->"; 53 cout<<data[num-1]<<endl; 54 return 0; 55 }