快速排序法

时隔几天,再一次的学习起了快速排序法。竟然自己已经写不出来了。只记得它大概的步骤。

照着书上的例子,自己又再重新写了一遍。

#include <stdio.h>

void print(int r[], int n)
{
    int i;
    for(i = 0; i < n; i++)
        printf("%d ", r[i]);
    puts("\n");
}

int KQPass(int r[], int low, int high)
{
    int temp = r[low];
    while(low < high)
    {
        while(low < high && r[high] >= temp)
            high --;
        if(low < high)
        {
            r[low] = r[high];
            low ++;
        }
        while(low < high && r[low] < temp)
            low ++;
        if(low < high)
        {
            r[high] = r[low];
            high --;
        }
    }
    r[low] = temp;
    return low;
}

void KSSort(int r[], int low, int high)
{
    int pos = KQPass(r, low, high);
    if(low < high)
    {
        pos = KQPass(r, low, high);
        KSSort(r, low, pos-1);
        KSSort(r, pos+1, high);
    }
}

int main()
{
    int a[10] = {3, 1, 5, 2, 7, 8, 9, 4, 6, 0};
    printf("before sort:\n");
    print(a, 10);
    KSSort(a, 0, 9);
    printf("sort after:\n");
    print(a, 10);
    return 0;
}

最后运行结果

 

KQpass函数表示一趟快速排序算法后的结果。返回的是中轴元素所在的位置。

快速排序法的时间复杂度为 O(nlog2n)

空间复杂度为 O(log2N)

快速排序法运用到了递归算法。

posted @ 2017-07-27 20:53  大波非猫  阅读(206)  评论(0编辑  收藏  举报