fragments

Nov 09, 2017

快速排序C语言递归实现

Last updated at: Nov 09, 2017

#include<stdio.h>
#include<stdlib.h>
#define SIZE 10

void quick_sort(int a[], int lo, int hi) {
    if (lo < hi) {
        int i = partition(a, lo, hi);
        quick_sort(a, lo, i - 1);
        quick_sort(a, i + 1, hi);
    }
}

int partition(int a[], int lo, int hi) {
    int pivot, i, j, t;
    pivot = a[lo];
    i = lo;
    j = hi + 1;

    while(1) {
        do ++i; while(a[i] <= pivot && i <= hi);
        do --j; while(a[j] > pivot);
        if (i >= j) break;

        t = a[i], a[i] = a[j], a[j] = t;
    }

    t = a[lo], a[lo] = a[j], a[j] = t;
    return j;
}

int main(){
    int array[SIZE] = {5, 4, 3, 1, -1, -3, 0, 10, 9, 8};
    quick_sort(array, 0, SIZE - 1);

    int i;
    for(i = 0; i < SIZE; ++i)
        printf("%d\n", array[i]);
    return EXIT_SUCCESS;
}

(137 words)