算法学习2:快速排序
快速排序算法的基本思想就是选择一个基准数,然后把小于基准数的数都扔到基准数左边,大于基准数的数都放到基准数右边,然后对基准数左右两边的两个子数组再重复这一过程(递归调用)。
示例:
#include<stdio.h> int a[101], n; // define 2 global variables void quicksort(int left, int right) { int i, j, t, temp; if (left > right) { return; } temp = a[left]; // base value i = left; j = right; while (i != j) { // from right to left while (a[j] >= temp && i < j) { j--; } // from left to right while (a[i] <= temp && i < j) { i++; } if (i < j) // if the 2 sentinals didn't meet { // swap the 2 numbers t = a[i]; a[i] = a[j]; a[j] = t; } } // set back the base value a[left] = a[i]; a[i] = temp; // recursive call quicksort(left, i - 1); // quick sort the left sub sequence quicksort(i + 1, right); // quick sort the right sub sequence } int main() { int i, j, t; scanf_s("%d",&n); for (i = 0; i < n; i++) { scanf_s("%d", &a[i]); } quicksort(0, n-1); for (i = 0; i < n; i++) { printf("%d ", a[i]); } getchar(); getchar(); return 0; }