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

    快速排序是一种分治排序算法,它的基本思想是:通过一趟排序将要排序的数据分割成独立的两部分,其中一部分的所有数据都比另外一部分的所有数据都要小,然后再按此方法对这两部分数据分别进行快速排序,整个排序过程可以递归进行,以此达到整个数据变成有序序列。

    1.代码实现

    以java实现为例:

    public class QuickSort {
        public static int[] quickSort(int[] nums,int start,int end) {
            int pivot = nums[start];
            int i = start;
            int j = end;
            while (i < j) {
                while (i < j && nums[j] > pivot) {//此处不能用大于等于(下面同理),否则当首位为最大值时会无法交换
                    j--;
                }
                while (i < j && nums[i] < pivot) {
                    i++;
                }
                if (nums[i] == nums[j] && i < j) {//这一步是处理示例序列中这种情况
                    i++;
                } else {
                    int temp = nums[i];
                    nums[i] = nums[j];
                    nums[j] = temp;
                }
            }
            if (i-1 > start) nums = quickSort(nums,start,i-1);
            if (j+1 < end) nums = quickSort(nums,j+1,end);
            return nums;
        }
        public static void main(String[] args) {
    //        int[] nums = new int[] { 9, 8, 7, 6, 5, 4, 3, 2, 10 };
            int[] nums = new int[] { 10, 8, 7, 6, 5, 4, 3, 2, 10 };
            int[] newNums = quickSort(nums,0,nums.length-1);
            for (int x : newNums) {
                System.out.print(x+" ");
            }
        }
    }

    2.数据运行解析 

    数据的分解示例如下:

    [10 8 7 6 5 4 3 2 10]
    ->[10 8 7 6 5 4 3 2 10]  第一次以下标为0的元素10开始比较,序列不变,此时i=j=8
    ->[2 8 7 6 5 4 3 10 10]  然后进入递归0-7之间序列排序,交换10和2,此时i=j=7
    ->[2 8 7 6 5 4 3 10 10]  然后进入递归0-6之间序列排序....
    .....

    3.复杂度分析

    快速排序的最差时间复杂度是O(n²),平均时间复杂度是O(nlogn),空间复杂度为T(nlogn)。

  • 相关阅读:
    new的实现原理
    call, apply, bind的内部实现原理
    redux基础第二讲——react-redux
    redux基础第一讲
    React组件的数据
    ES6中的super
    ES5和ES6中实现对象和继承的方法对比
    react组件的生命周期
    浅谈js继承的几种方法
    LeetCode 5274. Number of Ways to Stay in the Same Place After Some Steps
  • 原文地址:https://www.cnblogs.com/cykfory/p/14139296.html
Copyright © 2011-2022 走看看