zoukankan      html  css  js  c++  java
  • 算法学习之快速排序

    • 快速排序输采用分而治之的策略,将一个串分为两个串,分别进行排序
    • 具体实现方法:
      1. 在数组中找到基准pivot
      2. 分区partition操作:将所有小于pivot的元素放在pivot的前面,将所有大于pivot的元素放在pivot的后面
      3. 递归recursive操作:将两个子数组进行上面类似的排序
    • 效率分析:
    1. 时间复杂度:最佳好情况O(nlogn),数组中的每个元素都需要被循环遍历一次,以找到其位置,需要O(n),而每次遍历时都将数组给分区成2个部分,需要O(logn);最坏情况O(n^2)
    2. 空间复杂度:最好情况O(logn),最坏情况O(n)
    • 实现代码:

      

    void partition(int *arr,int l, int h)
    {
        if (l >= h) return;
        int i = l;
        int j = h;
        int key = arr[i];
        while (i < j) {
            while (i<j && (arr[j] > key)) j--;
            if(i<j) arr[i++] = arr[j];
            while (i<j && (arr[i] < key)) i++;
            if(i<j) arr[j--] = arr[i];
        }
        arr[i] = key;
        partition(arr, l, i-1);
        partition(arr, i+1, h);
    }
    
  • 相关阅读:
    git学习
    Command Line
    python之测试
    python之模块
    python之函数
    python之类
    python之错误和异常
    python之迭代器和生成器
    python之字典和集合
    python之列表和元组
  • 原文地址:https://www.cnblogs.com/wustlj/p/2712962.html
Copyright © 2011-2022 走看看