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)

    原地排序:是

    稳定排序:是

  • 相关阅读:
    ACM_求f(n)
    ACM_四数之和
    jQuery 3D旋转展示焦点图
    jQuery+CSS3动画相册特效
    jQuery/CSS3实现Android Dock效果
    html5/CSS3鼠标滑过图片特效插件
    CSS3定时提示动画特效
    日期选择插件
    HTML5/CSS3淡入淡出滑块焦点图
    HTML5/CSS3动画下拉菜单
  • 原文地址:https://www.cnblogs.com/zhanghaodong/p/10337943.html
Copyright © 2011-2022 走看看