Sort - Quick Sort detailed analysis

Quick sort of principle have been very clear, and now talk about the details of the code and processing methods

 1 #include<iostream>
 2 using namespace std;
 3 void quicksort(int* a, int low, int high)
 4 {
 5     if (low < high)
 6     {
 7         int begin = low;
 8         int end = high;
 9         int key = a[begin];
10         while (begin < end)
11         {
12             while (begin<end && a[end]>key)
13                 end--;
14             if (begin < end)
15                 a[begin++] = a[end];
16             while (begin < end && a[begin] < key)
17                 begin++;
18             if (begin < end)
19                 a[end--] = a[begin];
20         }
21         a[begin] = key;
22         quicksort(a, low, begin - 1);
23         quicksort(a, begin + 1, high);
24     }
25 
26 }
27 int main()
28 {
29     int b[6] = {3,4,6,1,2,5};
30     quicksort(b, 0, 5);
31     for (int i = 0;i < 6;i++)
32         cout << b[i] << endl;
33     return 0;
34 }

(This is the most basic version, if you have questions, please remind)

Code, I set the low and high for the beginning and end of the array, the array of attention to cross-border issues, an array of 10 digits inside, so high should be 9!

Then at the beginning of this if, this very clear instructions to the machine, we will look very clear principle, so if this is still very good.

The following is two while if, these two statements is determined and is used to exchange the first statement is a pointer (end) away from the rear forward, the second is (the begin) away from front to back, to find the corresponding elements to swap positions.

This intermediate a details, such as line 15, a [begin ++] = a [end] This statement is critical, the pointer automatically at the (if begin, on a later point, if End, just before the point a) understanding the future looks very clear, if there is no statement similar functions, the program should enter an infinite loop under certain conditions. (For example, when the begin = 3, end = 4, a [begin] = 1, a [end] = 1, under this condition, all the conditions are met, but he will be assigned to a brain without a front, a rear to previous).

The last parameter is recursive, should be the first parameter is an array, this needless to say, the second parameter is the beginning of the array to be processed, the third parameter is the end of the array to be processed

(For example, the first recursive call, low = 0, begin-1 = 2, since a total of six digits, and a [2] is the third number is a reference number, the reference numbers do not participate in another round of sorting , so this example which should be the sort of element 0,1)

 

Finally, give their own fuel!

Guess you like

Origin www.cnblogs.com/KeithTee/p/11707887.html