快排+java實現

來源:互聯網
上載者:User

標籤:max   tostring   print   class   partition   取出   array   quic   system   

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;        int minpos=low;        int maxpos=low;        if(a[mid]<a[minpos]) minpos=mid;        if(a[high]<a[minpos]) minpos=high;        if(a[mid]>a[maxpos]) maxpos=mid;        if(a[high]>a[maxpos]) maxpos=high;        if(low!=minpos&&low!=maxpos) pos=low;        if(mid!=minpos&&mid!=maxpos) pos=mid;        if(high!=minpos&&high!=maxpos) pos=high;        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));    }}

 

快排+java實現

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.