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

    快速排序原理:

    选择一个关键值作为基准值。比基准值小的都在左边序列(一般是无序的),比基准值大的都在右边(一般是无序的)。一般选择序列的第一个元素或最后一个元素(还可以3个元素(第一个,中间,最后一个)取中)。

    java代码:(随机选取一个基准值)

     public static void kuaisu(int[] arr, int start_index, int end_index) {
            if (start_index >= end_index) {
                return;
            }
            int pivot = partition(start_index, end_index);
            System.out.println("start_index:" + start_index + ",end_index:" + end_index + ",pivot:" + pivot);
            //将小于arr[pivot] 的数放在左边,大于arr[pivot] 的数放在右边
            pivot = shuaxin(arr, start_index, end_index, pivot);
    
            kuaisu(arr, start_index, pivot - 1);
            kuaisu(arr, pivot + 1, end_index);
        }
        public static int shuaxin(int[] arr, int start_index, int end_index, int pivot) {
            if (pivot < start_index || pivot > end_index) {
                return 0;
            }
    //        int i = start_index;
            for (int j = start_index; j <= end_index; j++) {
                if (j < pivot && arr[j] > arr[pivot]) {
                    swap(arr, pivot, j);
                    pivot = j;
                } else if (j > pivot && arr[j] < arr[pivot]) {
                    swap(arr, pivot, j);
                    int temp = pivot;
                    pivot = j;
                    j = temp;
                }
            }
            return pivot;
        }
       public static int partition(int start_index, int end_index) {
            int nextInt = RandomUtils.nextInt(end_index - start_index);
            return start_index + nextInt;
    
        }

    性能分析:

    时间复杂度:O(n*logN)

    空间复杂度:O(1)

    原地排序:是

    稳定排序:是

  • 相关阅读:
    前端展示(四)
    小谢第66问:页面关闭鼠标光标
    小谢第64问:nuxt项目中增加百度分析统计
    js 判断当前是手机还是电脑
    布谷鸟自定义教程
    vs code常用插件及配置
    小程序几件小事儿
    删除 json 数据中的某一项
    小程序图片预览
    小程序 navigator 取消点击效果
  • 原文地址:https://www.cnblogs.com/zhanghaodong/p/10337943.html
Copyright © 2011-2022 走看看