The fast sorting algorithm was first designed by Tony Hoare, the Turing prize winner. He has made outstanding contributions to the invention of formal method theory and is one of the greatest computer scientists in the last century. And this fast sorting algorithm is just one of his many contributions. What's more, the fast sorting algorithm we are learning now is listed as one of the top ten algorithms in the 20th century.

Fast sorting is actually the upgrade of the slowest bubbling sorting we thought before. They are all exchange sort. That is, it is realized through continuous comparison and mobile switching

Sorting, but its implementation, increases the distance between comparison and movement of records, moves records with larger keywords from the front directly to the back, and those with smaller keywords from the back to the front

So as to reduce the total number of comparisons and mobile exchanges.

Its basic idea is:

1. Select a reference value, we set the rightmost one as the reference value;

2. Traverse the whole interval, compare all numbers with the reference value and move the data so that:

1) the number smaller than the reference value is placed on the left side of the reference value;

2) the number larger than the reference value is placed on the right side of the reference value;

3. Divide and conquer algorithm: [left, right] - > [left, div-1] ∪ [div+1, right], and using the idea of recursion, the termination condition of recursion is size = 0 or size = 1 (there are no numbers in the interval or the interval has been ordered).

The implementation code is as follows:

#include <stdio.h> #include <stdlib.h> void Swap(int* a, int* b) { int temp = *a; *a = *b; *b = temp; } int Partition(int* arr, int left, int right) { int begin = left; int end = right; while (begin < end) { while (begin < end && arr[begin] <= arr[right]) { begin++; } while (begin < end && arr[end] >= arr[right]) { end--; } Swap(arr + begin, arr + end); } Swap(arr + begin, arr + right); return begin; } void _QuickSort(int* arr, int left, int right) { if (left == right) { //If there is only one number left in the interval return; } if (left > right) { //There are no numbers in the interval return; } int div = Partition(arr, left, right); _QuickSort(arr, left, div - 1); _QuickSort(arr, div + 1, right); } void QuickSort(int* arr, int size) { _QuickSort(arr, 0, size - 1); } void Print(int* arr, int size) { for (int i = 0; i < size; i++) { printf("%d ", arr[i]); } printf("\n"); } int main() { int arr[] = { 50, 10, 90, 30, 70, 40, 80, 60, 20 }; int size = sizeof(arr) / sizeof(arr[0]); printf("----------Test quick sort----------\n"); printf("Before sorting: "); Print(arr, size); QuickSort(arr, size); printf("Sorted by: "); Print(arr, size); system("pause"); return 0; }

Operation result: