1. 程式人生 > 其它 >演算法學習2:快速排序

演算法學習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; }