给力星

Web Developer

快速排序算法_C语言代码

数组下标可从0或1开始。

#include <stdio.h>
void quick_sort(int data[], int low, int high) {
    int i,j,pivot;
    if (low < high) {
        pivot = data[low];
        i = low;
        j = high;
        while (i<j) {
            while (i<j && data[j]>=pivot) j--;
            if (i<j) data[i++] = data[j];
            while (i<j && data[i]<=pivot) i++;
            if (i<j) data[j--] = data[i];
        }
        data[i] = pivot;
        quick_sort(data, low, j-1);
        quick_sort(data, i+1, high);
    }
}

int main() {
    int n,i;
    int data[1000000];
    scanf("%d", &n);
    for (i = 0; i < n; i++) {
        scanf("%d", &data[i]);
    }
    quick_sort(data, 0, n-1);
    for (i = 0; i < n; i++) {
        printf("%d ", data[i]);
    }
    return 0;
}