Quick sorting is an algorithm with high efficiency. The idea of the algorithm is to extract an element to be sorted and try to swap the elements smaller than him to his left, the element greater than him is exchanged on the right side of him, and then the left and right sides are recursively performed, until there is only one element on the left and right sides. Thus the overall sorting is achieved. The code for C ++ implementation is as follows:
// Quick Sort (recursive) template <typename T> void quick_sort (T * arr, int B, int e) {If (B <E) {int I = B, j = E; t x = arr [I]; while (I <j) {While (I <J & arr [J]> = x) -- J; if (I <j) {arr [I] = arr [J]; ++ I;} while (I <J & arr [I] <= X) ++ I; if (I <j) {arr [J] = arr [I]; -- J ;}} arr [I] = x; quick_sort (ARR, B, i-1); quick_sort (ARR, I + 1, E );}}
However, Recursive Algorithms for fast sorting are unstable. If the elements to be sorted do not meet the design requirements of the algorithm, for example, they are already in reverse or forward order, this not only reduces sorting efficiency, but also leads to a rapid increase in recursive depth and even stack overflow.
Although random subscripts or other methods are used for optimization in algorithm processing, it only reduces the probability and does not prevent stack overflow.
Therefore, this algorithm class can be implemented in a non-recursive manner to solve the problem of stack overflow. The principle is to sort the left side in a loop and then sort the right side in a loop. The C ++ code is as follows:
Template <typename T> void quick_sort_no_recursive_left (T * arr, int B, int e) {int I, j; loop: If (B <E) {I = B; j = E; t x = arr [I]; while (I <j) {While (I <J & arr [J]> = x) -- J; if (I <j) {arr [I] = arr [J]; ++ I;} while (I <J & arr [I] <= X) + + I; if (I <j) {arr [J] = arr [I]; -- J ;}} arr [I] = x; E = I-1; goto loop ;}}template <typename T> void quick_sort_no_recursive_right (T * arr, int B, int e) {int I, j; loop: If (B <E) {I = B; j = E; t x = arr [I]; while (I <j) {While (I <J & arr [J]> = X) -- J; if (I <j) {arr [I] = arr [J]; ++ I;} while (I <J & arr [I] <= X) ++ I; if (I <j) {arr [J] = arr [I]; -- J ;}} arr [I] = x; B = I + 1; goto loop; }}// fast sorting (non-recursive) template <typename T> void quick_sort_no_recursive (T * arr, int B, int e) {quick_sort_no_recursive_left (ARR, B, e); quick_sort_no_recursive_right (ARR, B, E );}