線性選擇 java描述

來源:互聯網
上載者:User

標籤:turn   演算法   out   color   col   ges   string   length   ati   

public class FindKthLargestNum {    public static void main(String[] args) {                int[] arr= {1,3,5,7,9,10,8,6,4,2,11,13,15,17,19,20,18,16,14,12};                for(int i=0;i<arr.length;i++) {            System.out.print(select(arr,0,arr.length-1,i+1)+" ");        }    }    //select演算法        public static int select(int[] array,int begin,int end,int k) {        //begin到end不超過5個數,採用冒泡演算法先排序後將第k小的數輸出,也是遞迴的出口        if(end-begin+1<=5) {            bubbleSort(array,begin,end);            return array[begin+k-1];        }        //將數組中的資料按五個一組分組並用冒泡排序將每組中的五個數排序,找出各組的中值,依次放在數組的前端        //這樣就可以對數組的第0到group個數遞迴調用select排序        int group=(end-begin+1)/5;        for(int i=0;i<group;i++) {            int left=begin+i*5;            int right=begin+(i+1)*5-1;            int mid=(left+right)/2;            bubbleSort(array,left,right);            int temp=array[begin+i];            array[begin+i]=array[mid];            array[mid]=temp;        }        //遞迴調用select找出各組中值的中值        int m=select(array,begin,begin+group-1,(group+1)/2);        //將比m小的值放在m左邊,比m大的放在m右邊,並返回m的下標j        int j=partition(array,begin,end,m);        //從begin開始,j前面的元素個數為leftnum        int leftnum=j-begin;        if(k==leftnum+1) {            return array[j];        }        else if (k<=leftnum+1) {            return select(array,begin,j-1,k);        }else{                        return select(array,j+1,end,k-leftnum-1);        }            }    //冒泡排序    public static void bubbleSort(int[] arr,int begin,int end) {        for(int i=begin,k=0;i<end;i++,k++) {            for(int j=begin;j+1<=end-k;j++) {                if(arr[j]>arr[j+1]) {                    int temp=arr[j+1];                    arr[j+1]=arr[j];                    arr[j]=temp;                }            }        }    }    //把比X小的房X左邊,比X大的放X右邊,返回排序後X的下標    public static int partition(int[] arr,int begin,int end,int x) {        int i=begin;        int j=end;        while(true) {            while(arr[i]<x&&i<end) {                ++i;            }            while(arr[j]>x) {                --j;            }            if(i>=j) {                break;            }            int temp=arr[i];            arr[i]=arr[j];            arr[j]=temp;                }        return j;    }}

 

線性選擇 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.