java 堆排序的實現

來源:互聯網
上載者:User

標籤:

堆就是一個完全二叉樹,堆要求是指 該節點大於它的兩個子節點。而兩個位元組點大小不一定。

堆排序的最壞時間複雜度為nlog(n),平均也為nlog(n),佔用空間為o(1),是一種比較排序演算法。

堆排序也可以用於找最大的k個數。時間複雜度為klog(n),因為建堆後,每次迴圈實際上都產生一個最大數。

下面見代碼:

//從小到大排序public class HeapSort {    private int[] A;    private int heapSize;    //建構函式,傳入待排序數組    public HeapSort(int[] A){        this.A = A;    }    public int[] getSortedArray(){        return A;    }        //從節點i出發,使得父節點的數不小於子節點的數    private void heapify(int i) {        //加1、加2後才是該節點的兩個子節點        int left = 2*i + 1;        int right = 2*i + 2;        int largest = 0;                //取得該節點、兩個子節點中最大的編號        if (left < heapSize &&  A[left] > A[i]) {            largest = left;        }else {            largest = i;        }                if (right < heapSize && A[right] > A[largest]) {            largest = right;        }        //若最大編號不是它,則繼續建堆,否則就滿足堆要求        if (largest != i) {            int temp = A[i];            A[i] = A[largest];            A[largest] = temp;            heapify(largest);        }    }        private void buildHeap(){        heapSize = A.length;        for (int i = (heapSize/2 - 1); i >= 0; i--) {            heapify(i);        }    }        private void heapSort(){        buildHeap();        int temp;        for (int i = A.length-1; i > 0; i--) {            temp = A[i];            A[i] = A[0];            A[0] = temp;            heapSize--;            heapify(0);        }    }        public static void main(String[] args) {
//測試案例 int[] array = {16,4,10,14,7,9,3,2,8,1,5,3,6,100}; HeapSort heapSort = new HeapSort(array); heapSort.heapSort(); for (int i : heapSort.A) { System.out.println(i); } }}

 

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.