Fast sorting is the same as Merge Sorting.
The most critical step is decomposition. For example, an array A [p.. r] is decomposed. It is divided into two sub-arrays, A [p. q-1] and A [q + 1. r]. Each element in A [p. q-1] is less than or equal to A [q], and each element in A [q + 1. r] is greater than or equal to A [q].
Pseudo code:
1 PARTITION (A, p, r) 2 {3 x = A [r]; 4 I = p-1; 5 for j = p to r-1 6 if A [j] <= x 7 I = I + 1 8 exchange A [I] with A [j] 9 exchange A [I + 1] with A [r] 10 return I + 111}View Code
Analysis: first, select the last element of the array as the principal element. I is set to the first element subscript minus 1. A [p .. the elements in r-1] are compared with the principal component in sequence. If it is smaller than the principal component, it is exchanged with A [I + 1, I + 1 (the first one is smaller than the principal element to the first position of the array, and the second one is smaller than the principal element to the second position of the array ......). After the loop ends, the elements of the sub-array A [p. I] are smaller than or equal to the principal element, and the elements of the sub-array A [I + 1. r-1] are greater than the principal element. Finally, the primary element and A [I + 1] are exchanged. Last array A [p .. r] is divided into two sub-arrays, the sub-array A [p .. i] elements are less than or equal to A [I + 1], sub-array A [I + 2 .. r] is greater than A [I + 1].
Legend:
Finally, we use quick sorting to sort arrays.
Pseudo code:
1 QUICKSORT (A, p, r) 2 if p <r3 q = PARTITION (A, p, r) 4 QUICKSORT (A, p, q-1) 5 QUICKSORT (, q + 1, r)View Code
When p is less than or equal to r, there is only one element in the array, which is obviously sorted. Otherwise, it is decomposed into two sub-arrays and uses recursive fast sorting.
If the two sub-arrays contain n-1 and 0 elements, T (n) = O (n ^ 2) is the worst case for quick sorting ). T (n) = O (nlgn) on average)
C ++ code
1 # define EXCHANGE (a, B) int temp = a; a = B; B = temp; 2 3 int partition (int A [], int p, int r) 4 {5 int x = A [r]; 6 int I = p-1; 7 8 for (int j = p; j <r; ++ j) 9 {10 if (A [j] <x) 11 {12 ++ I; 13 EXCHANGE (A [I], A [j]) 14} 15} 16 17 EXCHANGE (A [I + 1], A [r]); 18 19 return I + 1; 20} 21 22 // fast sorting, average time complexity T (n) = O (nlgn) 23 void Quick_sort (int A [], int p, int r) 24 {25 if (p <r) 26 {27 int q = partition (A, p, r); 28 Quick_sort (A, p, q-1); 29 Quick_sort (A, q + 1, r ); 30} 31}View Code