博客
关于我
【算法】————5、快速排序
阅读量:172 次
发布时间:2019-02-28

本文共 1543 字,大约阅读时间需要 5 分钟。

快速排序是一种高效的排序算法,以分治法为核心思想。其基本原理是通过选择一个基准值(pivot),将数组分为两部分:一部分元素小于基准值,另一部分元素大于基准值。随后递归对这两部分分别进行排序,最终达到整个数组有序。

快速排序的核心操作是分区(partition),即将数组划分为两部分。一旦完成分区,基准值就位于中间位置。接着对左右两部分递归进行排序。

代码实现

以下是快速排序的两种实现方式:

JavaScript实现

function quickSort(array, left, right) {    if (array.constructor !== Array || typeof left !== 'number' || typeof right !== 'number') {        return '输入错误';    }    if (left >= right) {        return array;    }    const pivot = array[right];    let i = left;    while (i < right && array[i] <= pivot) {        i++;    }    [array[left], array[i]] = [array[i], array[left]];    return quickSort(array, left, i - 1).concat(        [pivot],        quickSort(array, i + 1, right)    );}

Java实现

public class QuickSort {    public static void sort(int[] array) {        sort(array, 0, array.length - 1);    }    private static void sort(int[] array, int low, int high) {        if (low >= high) {            return;        }        int pivot = array[high];        while (high >= low && array[high] <= pivot) {            high--;        }        array[low] = array[high];        array[high] = pivot;        sort(array, low, high - 1);        sort(array, high + 1, high);    }}

性能与复杂度

快速排序的时间复杂度在大多数情况下为O(n log n),但在极端情况下(如数组已排序)会退化为O(n²)。其空间复杂度在最好情况下为O(log n),但在最坏情况下可能达到O(n²)。

为了提升性能,建议在每次划分时选择中间位置的元素作为基准值,这种方法被称为“三者取中”法。这样可以有效降低最坏情况下的时间复杂度。

优化方法

  • 选择中间位置的元素作为基准值:通过选择数组中间位置的元素作为基准值,可以减少递归深度,提高性能。
  • 对短数组优先排序:在每次划分后,先对较短的子数组进行排序,以减少递归深度。
  • 多次优化基准选择方法:除了中间位置的元素,还可以考虑其他基准选择策略,如基于数值的中位数等,进一步提升性能。
  • 通过上述优化方法,快速排序的时间复杂度可以得到显著提升,使其在各种场景下都能保持较高的效率。

    转载地址:http://bvwj.baihongyu.com/

    你可能感兴趣的文章
    npm build报错Cannot find module ‘webpack‘解决方法
    查看>>
    npm ERR! ERESOLVE could not resolve报错
    查看>>
    npm ERR! fatal: unable to connect to github.com:
    查看>>
    npm ERR! Unexpected end of JSON input while parsing near '...on":"0.10.3","direc to'
    查看>>
    npm ERR! Unexpected end of JSON input while parsing near ‘...“:“^1.2.0“,“vue-html-‘ npm ERR! A comp
    查看>>
    npm error Missing script: “server“npm errornpm error Did you mean this?npm error npm run serve
    查看>>
    npm error MSB3428: 未能加载 Visual C++ 组件“VCBuild.exe”。要解决此问题,1) 安装
    查看>>
    npm install CERT_HAS_EXPIRED解决方法
    查看>>
    npm install digital envelope routines::unsupported解决方法
    查看>>
    npm install 卡着不动的解决方法
    查看>>
    npm install 报错 EEXIST File exists 的解决方法
    查看>>
    npm install 报错 ERR_SOCKET_TIMEOUT 的解决方法
    查看>>
    npm install 报错 Failed to connect to github.com port 443 的解决方法
    查看>>
    npm install 报错 fatal: unable to connect to github.com 的解决方法
    查看>>
    npm install 报错 no such file or directory 的解决方法
    查看>>
    npm install 权限问题
    查看>>
    npm install报错,证书验证失败unable to get local issuer certificate
    查看>>
    npm install无法生成node_modules的解决方法
    查看>>
    npm install的--save和--save-dev使用说明
    查看>>
    npm node pm2相关问题
    查看>>