排序算法(快速排序)

快速排序算法有几种种优化方式:基准点的选择,减去不必要的交换位置,优化小数组时的优化,递归的优化(在数组长度很短,用直接插入算法就行了)

时间复杂度(nlog2n)

public class QuickSort {
    
    public static void main(String[] args) {
        int a[]={1,3,5,2,7,7,4,9};
        sort(a, 0, 7);
        for (int i = 0; i < a.length; i++) {
            System.out.print(a[i]);
        }
    }
    
    public static void sort(int a[],int low,int high){
        
        int point=a[low];//开始时,基准点在数组的最开始的位置
        if(low<high){
            point=patertion(a,low,high);
            sort(a,low,point-1);//递归左边
            sort(a,point+1,high);//递归右边
            
        }
        
    }

    private static int patertion(int[] a, int low, int high) {
        int point=a[low];
        while(low<high){
            while(low<high&&a[high]>=point){
                    high--;
                }
                a[low]=a[high];
                //swap(a,low,high);//我们交换可以变成赋值
                
            
            while(low<high&&a[low]<=point){
                low++;
                }
                a[high]=a[low];
                //swap(a,low,high);//我们交换可以变成赋值,最后low的位置存的point,结束后赋值回去a[low]=point;
                
        }    
        a[low]=point;
        return low;
    }

//    private static void swap(int[] a, int low, int high) {
//        int temp;
//        temp=a[high];
//        a[high]=a[low];
//        a[low]=temp;
//    }
//    
    

}

原文地址:https://www.cnblogs.com/LvLoveYuForever/p/5744706.html