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;
        }
  • 相关阅读:
    简单的StringBuffer实现
    Java-HashMap、HashSet、hashTable
    JavaScript 引用错误
    使用jconsole分析内存情况-JVM
    Thread 与 Runnable 混合使用测试
    裴波那序列-JAVA实现
    多线程之----------线程池
    winform 控件拖拽和缩放
    C# 使用Process调用外部程序中所遇到的参数问题
    winform textbox 的自动实现功能
  • 原文地址:https://www.cnblogs.com/myronxy/p/3176436.html
Copyright © 2011-2022 走看看