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)

    原地排序:是

    稳定排序:是

  • 相关阅读:
    Uva 11401 数三角形
    Uva 11538 象棋中的皇后
    数学基础——基本计数方法
    八数码问题
    python 爬poj.org的题目
    python 爬图片
    hiho 第135周 九宫
    Uva 11464 偶数矩阵
    BZOJ 1001 [BeiJing2006]狼抓兔子
    LA 3708 墓地雕塑
  • 原文地址:https://www.cnblogs.com/zhanghaodong/p/10337943.html
Copyright © 2011-2022 走看看