zoukankan      html  css  js  c++  java
  • 快速排序法

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

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

    #include <stdio.h>
    
    void print(int r[], int n)
    {
        int i;
        for(i = 0; i < n; i++)
            printf("%d ", r[i]);
        puts("
    ");
    }
    
    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:
    ");
        print(a, 10);
        KSSort(a, 0, 9);
        printf("sort after:
    ");
        print(a, 10);
        return 0;
    }

    最后运行结果

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

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

    空间复杂度为 O(log2N)

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

  • 相关阅读:
    JQuery扩展方法
    RabbitMQ消息机制广播分发
    RabbitMQ消息机制单人分发
    对函数的参数求和
    ajax jsonp
    绑定函数bind()
    this 指向
    DOM兼容
    命名空间 namespace
    开始看编写高质量的代码
  • 原文地址:https://www.cnblogs.com/hello-lijj/p/7247319.html
Copyright © 2011-2022 走看看