sort
Re-adjust the order of a set of ordered elements by size (as long as the definition returns true or false comparisons, not necessarily numerical comparisons).
Quick sort
Quick sorting is similar to merge sorting, but merge sorting is to sort and merge elements in array length (1,2...n/4,n/2,n) sequentially, first sorting in a small range (2,4,8...) and then merging arrays by insertion sorting; Quick sorting first divides the large range sorting into two parts (middle point P, left arr [L] <= arr [P] <= right arr[R]), and then recursively in a small range.
Algorithm implementation
/* Elr Sort Quick Source */ #include <stdio.h> #include <stdlib.h> #include "elr_sort_quick.h" void exchange(long long int* arr, int p1, int p2) { long long int tmp = arr[p1]; arr[p1] = arr[p2]; arr[p2] = tmp; } int partition(long long int* arr, int left, int right) { long long int tmp = arr[right]; int i = left - 1; int j; for (j = left; j < right; j++) { if (arr[j] <= tmp) { i++; exchange(arr, i, j); } } exchange(arr, i + 1, right); return i + 1; } void quickSort(long long int* arr, int left, int right) { if (left < right) { int sep = partition(arr, left, right); printf("left:%d,right:%d,position:%lld,partition:%d ", left, right, arr[sep], sep); int i; for (i = left; i <= right; i++) { printf("%lld ", arr[i]); } printf("\n"); quickSort(arr, left, sep - 1); quickSort(arr, sep + 1, right); } } long long int* elrSortQuick(long long int* arr, int len) { quickSort(arr, 0, len - 1); return arr; }
Debugging call
#include <stdio.h> #include <stdlib.h> #include "elr_sort_quick.h" int main(int argc, char **argv){ int i; long long int arr[] = {6, 2, 4, 1, 3, 5, 0, 8, 9, 7}; elrSortQuick(arr, 10); printf("%d\n", (int)(sizeof(arr) / sizeof(long long int))); for (i = 0; i < 10; i++) { printf("%lld ", arr[i]); } printf("\n"); return 0; }
output
left:0,right:9,position:7,partition:7 6 2 4 1 3 5 0 7 9 8 left:0,right:6,position:0,partition:0 0 2 4 1 3 5 6 left:1,right:6,position:6,partition:6 2 4 1 3 5 6 left:1,right:5,position:5,partition:5 2 4 1 3 5 left:1,right:4,position:3,partition:3 2 1 3 4 left:1,right:2,position:1,partition:1 1 2 left:8,right:9,position:8,partition:8 8 9 10 0 1 2 3 4 5 6 7 8 9