快排+java實現


import java.util.Arrays;

public class QuickSort {
    //三數取中法。取出不大不小的那個位置
    public static int getPivotPos(int[] a,int low,int high) {
        int mid=(low+high)/2;
        int pos=low;
        if(a[mid]<a[low]) {
            int temp=a[low];
            a[low]=a[mid];
            a[mid]=temp;
        }
        if(a[high]<a[low]) {
            int temp=a[high];
            a[high]=a[low];
            a[low]=temp;
        }
        if(a[high]<a[mid]) {
            int temp=a[high];
            a[high]=a[mid];
            a[mid]=temp;
        }
        pos=mid;
        return pos;
    }
    //划分,取出樞紐位置
    public static int partition(int[] a,int low,int high) {
        int pivotpos=getPivotPos(a,low,high);
        int pivot=a[pivotpos];
        int temp=pivot;
        a[pivotpos]=a[low];
        a[low]=temp;
        while(low<high) {
            while(low<high&&a[high]>=pivot) high--;
                a[low]=a[high];
            while(low<high&&a[low]<=pivot)  low++;
                a[high]=a[low];
        }
        a[low]=pivot;
        return low;
    }
    //快排
    public static void quickSort(int[] a,int low,int high) { 
        if(low<high) {
            int pivotpos=partition(a,low,high);
            quickSort(a,low,pivotpos-1);
            quickSort(a,pivotpos+1,high);
        }
    }
    //重載快排
    public static void quickSort(int[] a) {
        if(a.length==0)
            return;
        int low=0;
        int high=a.length-1;
        quickSort(a,low,high);
    }
    
    public static void main(String[] args) {
        int[] a= {12,32,24,99,54,76,48};
        quickSort(a);
        System.out.println(Arrays.toString(a));
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM