The Fast sorting algorithm (QuickSort) is one of the most commonly used sorting algorithms. A suggestion for explaining his ideas reference: six quick sorting of Vernacular classical algorithm series quick fix
The idea of the article is simply: divide and conquer and dig the pit pits
I simply follow (1) The first digit of the storage Array (2) from backward to forward comparison (3) from front to back. In this order, a version is written:
void QuickSort (int* arr, int start, int end) {if (start = = end) Return;int key = Arr[start];int head = start;int tail = end; while (head! = tail) {while (Key < Arr[tail]) Tail--;arr[head] = Arr[tail];head++;while (Key > Arr[head]) head++;arr[ Tail] = arr[head];tail--;} At this point, head = = Endquicksort (arr, start, head-1); QuickSort (arr, head + 1, end); return;}
The groove is totally wrong, okay, dead loop.
After checking it out, it was because you didn't notice that because key holds a value, there is no key value in the array (the array value changes dynamically ). You cannot rely solely on the size of the key to determine the end point of the inner while.
Need to add head < tail restrictions. In this way, the operation after the while is also optional.
Also, since the iteration range has only one number left, QuickSort (arr, start, head-1); In Start > head-1, you cannot jump out of an iteration. Similarly, QuickSort (arr, head + 1, end); Also. The iteration endpoint needs to be modified.
Finally, Key doesn't put back the array ...
The code after the modification is:
void QuickSort (int* arr, int start, int end) {if (Start >= end) Return;int key = Arr[start];int head = start;int tail = E Nd;while (head = tail) {while (Key < Arr[tail] && head < tail) tail--;if (Head < tail) {Arr[head] = Arr[tail] ; head++;} while (Key > Arr[head] && head < tail) head++;if (Head < tail) {Arr[tail] = arr[head];tail--;}} At this point, head = = Endarr[head] = Key;quicksort (arr, start, head-1); QuickSort (arr, head + 1, end); return;}
Finally, the right ... Sure enough, you still need an instance to run to find the problem.
Fast sorting for C/C + +