1 #include<iostream> 2 #include<ctime> 3 using namespace std; 4 5 6 int RandomInRange(int start, int end) { 7 srand((unsigned)time(NULL)); 8 int value = rand()% (end - start + 1) + start; 9 return value; 10 } 11 12 void Swap (int *a, int *b) { 13 int temp; 14 temp = *a; 15 *a = *b; 16 *b = temp; 17 } 18 int Partition(int data[], int length, int start, int end) { 19 if(data == NULL || length <= 0 || start < 0 || end >= length) { 20 throw new std::exception("Invaild Parameters"); 21 } 22 23 int index = RandomInRange(start, end); 24 Swap(&data[index], &data[end]);//将选取的数字放到最后 25 26 int small = start - 1; 27 for(index = start; index < end; index++) {//此处是从一边遍历,另外可以从两边开始遍历 28 if(data[index] < data[end]) { 29 ++small;//位置在small之前的数字,都是比选取的数字小的 30 if(small != index) 31 Swap(&data[index], &data[small]); 32 } 33 } 34 ++small; 35 Swap(&data[small], &data[end]);//最后将选取的数字放到合适的位置 36 return small; 37 } 38 39 void QuickSort(int data[], int length, int start, int end) { 40 if(start == end) 41 return; 42 int index = Partition(data, length, start, end); 43 if (index > start) 44 QuickSort(data, length, start, index-1); 45 if (index < end) 46 QuickSort(data, length, index+1, end); 47 } 48 int main() 49 { 50 //cout << RandomInRange(1, 10) << endl; 51 int data[] = {2,4,3,1,5,7,6}; 52 QuickSort(data, 7, 0, 6); 53 for(int i = 0; i < 7; i++) { 54 cout << data[i] << endl; 55 } 56 return 0; 57 }