java語言實現堆排序

來源:互聯網
上載者:User

標籤:int   string   ring   ++   pac   print   static   ext   and   

package secondChapter;import java.util.Random;public class HeapSort {        private static int AHeapSize;        public static void main(String[] args) {                HeapSort hs = new HeapSort();        int[] A = new int[10];        //產生隨機數組        for(int i=0;i<A.length;i++){            A[i] = hs.generateRandomInt(50);        }        System.out.print("Original array:");        for (int i = 0; i < A.length; i++) {            System.out.print(A[i]+" ");        }        System.out.println();                hs.heap_sort(A);                System.out.print("Sorted array: ");        for (int i = 0; i < A.length; i++) {            System.out.print(A[i]+" ");        }    }        //HEAPSORT過程    public void heap_sort(int[] A) {        AHeapSize = A.length;        build_max_heap(A);                System.out.print("build_max_heap: ");        for (int i = 0; i < A.length; i++) {            System.out.print(A[i]+" ");        }        System.out.println();                        for(int i=A.length;i>1;i--){            int temp = A[0];            A[0] = A[i-1];            A[i-1] = temp;                        AHeapSize -= 1;            max_heapify(A,1);        }    }        //HUILD-MAX-HEAP過程    public void build_max_heap(int[] A) {        for(int i=A.length/2;i>0;i--){            max_heapify(A,i);        }    }        //MAX-HEAPIFY過程    public void max_heapify(int[] A, int i) {    //i為 元素下標+1        int l = 2*i;        int r = 2*i+1;                int largest;        if(l<=AHeapSize && A[l-1]>A[i-1]){            largest = l;        }else{            largest = i;        }        if(r<=AHeapSize && A[r-1]>A[largest-1]){            largest = r;        }        if(largest!=i){            int temp = A[i-1];            A[i-1] = A[largest-1];            A[largest-1] = temp;                        max_heapify(A, largest);        }    }        private Random rd = new Random();    public int generateRandomInt(int bound) {        return rd.nextInt(bound);    }    }

輸出結果:

Original array:40 44 11 43 25 0 7 14 34 14
build_max_heap: 44 43 11 40 25 0 7 14 34 14
Sorted array: 0 7 11 14 14 25 34 40 43 44

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.