Code implements a recursive array of quick sort , wherein the limit is input from the random number has to sort the file number data (random number generation and writing process of file have been written in the previous chapter).
The main algorithm using sentinel element of the data block , the recursive implement sorting after infinite subdivision.
Also by using the code clock function on the execution time of the algorithm for calculating the efficiency of the evaluation algorithm .
In order to verify the results of sorting, the output content code to achieve the sorted into the same folder under sort_number.txt file.
. 1 #include <the iostream> 2 #include <the fstream> . 3 #include <the cstdlib> . 4 #include <the ctime> . 5 #include <algorithm> . 6 the using namespace STD; . 7 #define limit 100000 . 8 . 9 void quicksort ( int A [], int Low, int High) 10 { . 11 IF (Low <High) { // recursive termination condition 12 is int I = Low, J = High; // use i, j array is ordered in the corresponding section; 13 is intA = X [Low]; // the first element of the array as a sentinel, sentry elements taken this way 14 15 the while (I < J) { 16 the while (I <A && J [J]> = X) . 17 J,; // right to left looking sentinel element is smaller than a first element 18 is IF (I < J) { . 19 a [I] = a [J]; 20 is I ++; // the first found small sentinel assigned to the element value of the element to the first element, and the lower bound (i) a shift back 21 is } 22 is 23 is the while (I <J && a [I] <= X) 24 I ++; //Looking from left to right the first element is larger than the sentinel element 25 IF (I < J) { 26 is A [J] = A [I]; 27 J, ; 28 } // the first one found is greater than the sentinel element value is assigned to the element at index j of the element, and the upper bound (j) to a forward 29 } 30 a [i] = X; // the sentinel assigned to the index of position i, i before Sentinel elements than small elements, elements of the element than the Sentinel large i 31 is 32 quicksort (a, Low, I- . 1 ); // in two parts before and after the element recursive sort sentinel 33 is quicksort (a, i + . 1 , High) ; 34 is } 35 } 36 int main(void) 37 { 38 ifstream fin; 39 ofstream fout; 40 int x; 41 int i; 42 int a[limit]; 43 44 fin.open("random_number.txt"); 45 if(!fin){ 46 cerr<<"Can not open file 'random_number.txt' "<<endl; 47 return -1; 48 } 49 time_t first, last; 50 51 52 for(i=0; i<limit; i++){ 53 fin>>a[i]; 54 } 55 fin.close(); 56 57 first = clock(); 58 59 quicksort(a,0,limit-1); 60 61 last = clock(); 62 63 fout.open("sort_number.txt"); 64 65 if(!fout){ 66 cerr<<"Can not open file 'sort_number.txt' "<<endl; 67 return -1; 68 } 69 for(i=0; i<limit; i++){ 70 fout<<a[i]<<endl; 71 } 72 73 fout.close(); 74 75 cout<<"Sort completed (already output to file 'sort_number.txt')!"<<endl; 76 cout<<"Time cost: "<<last-first<<endl; 77 78 return 0; 79 }