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;
        }
  • 相关阅读:
    html表单的创建
    mysql数据库连接标准操作
    关于Apache+MySQL+PHP下载及配置注意事项
    两个范例
    Stack类
    Collections类集
    key可以重复的map集合:IdentityHashMap
    foreach对集合的输出作用
    ListIterator接口
    【官方方法】xcode7免证书真机调试
  • 原文地址:https://www.cnblogs.com/myronxy/p/3176436.html
Copyright © 2011-2022 走看看