zoukankan      html  css  js  c++  java
  • 基于交换的排序算法

    基于交换的排序算法:冒泡排序,快速排序。

    冒泡排序:总的时间复杂度O(n2)

        /*
         * 冒泡排序
         */
        public static void bubbleSort(int[] array, int length){
            for(int i=1; i<length; i++){
                for(int j=0;j<length-i;j++){
                    if(array[j]>array[j+1]){
                        int temp = array[j];
                        array[j]=array[j+1];
                        array[j+1]=temp;
                    }
                }
            }
        }

    快速排序:通过选择pivot(枢轴或者支点),将原始数组分为两部分,前一部分比pivot小,后一部分比pivot大,然后递归下去,最终得到排好序的数组。
    代码中,是默认选择数组的第一个元素作为pivot的。

    平均时间复杂度:O(n*logn)

    若初始数组基本有序,选择第一个作为pivot,快速排序将蜕化为冒泡排序,因此对于pivot的选取非常重要,通常是从start, middle, end三个数组元素中选择其中一个。

        /*
         * 快速排序
         */
        public void quickSort(int[] array, int start, int end ){
            if(start<end){
                int pivotKey=pivotKey(array,start,end);
                quickSort(array,start,pivotKey-1);
                quickSort(array,pivotKey+1,end);
            }
            
        }
        
        public int pivotKey(int[] array, int start, int end){
            int temp=array[start];
            while(start<end){
                while(start<end&&temp<=array[end]) end--;
                array[start]=array[end];
                while(start<end&&temp>=array[start])start++;
                array[end]=array[start];
            }
                    
            array[start]=temp;
            
            return start;
        }
  • 相关阅读:
    Jane Austen【简·奥斯汀】
    I Like for You to Be Still【我会一直喜欢你】
    Dialogue between Jack and Rose【jack 和 Rose的对话】
    git删除远程.idea目录
    码云初次导入项目(Idea)
    DelayQueue 订单限时支付实例
    eclipse安装spring的插件
    redis安装命令
    log4j详解
    jstree API
  • 原文地址:https://www.cnblogs.com/myronxy/p/3176436.html
Copyright © 2011-2022 走看看