排序算法(5)--快速排序

快速排序,分治法思想,递归实现:
#include <stdio.h>
#include <stdlib.h>

void quickSort(int a[], int low, int high);

int main()
{
    int n, i;
    printf("Input n:\n");
    scanf("%d", &n);
    int *a = malloc(sizeof(int) * n);

    for(i = 0; i < n; i++)
        scanf("%d", &a[i]);

    //sort
    quickSort(a, 0, n - 1);

    //print
    printf("After sorted:\n");
    for(i = 0; i < n; i++)
        printf("%d ", a[i]);
    printf("\n");

    return 0;
}

void quickSort(int a[], int low, int high)
{
    int i, j, key;
    i = low, j = high, key = a[low];

    if(low >= high) return ;

    while(i < j){
        while(i < j && a[j] >= key) --j;
        a[i] = a[j];

        while(i < j && a[i] <= key) ++i;
        a[j] = a[i];
    }
    a[i] = key;

    quickSort(a, low, i - 1);
    quickSort(a, i + 1, high);
}
点赞