java排序演算法_013堆排序(Heapsort)

來源:互聯網
上載者:User
package com.arithmetic;//堆排序(Heapsort)是指利用堆這種資料結構所設計的一種排序演算法。堆是一個近似完全二叉樹的結構,//並同時滿足堆性質:即子結點的索引值或索引總是小於(或者大於)它的父節點。public class Test_wzs013 {private static int[] sort = new int[] { 10, 3, 5, 7, 9, 1, 4, 2, 6, 8 };public static void main(String[] args) {buildMaxHeapify(sort);heapSort(sort);print(sort);}private static void buildMaxHeapify(int[] data) {// 沒有子節點的才需要建立最大堆,從最後一個的父節點開始int startIndex = getParentIndex(data.length - 1);// 從尾端開始建立最大堆,每次都是正確的堆for (int i = startIndex; i >= 0; i--) {maxHeapify(data, data.length, i);}}/** * 建立最大堆 *  * @param data * @param heapSize *            需要建立最大堆的大小,一般在sort的時候用到,因為最多值放在末尾,末尾就不再歸入最大堆了 * @param index *            當前需要建立最大堆的位置 */private static void maxHeapify(int[] data, int heapSize, int index) {// 當前點與左右子節點比較int left = getChildLeftIndex(index);int right = getChildRightIndex(index);int largest = index;if (left < heapSize && data[index] < data[left]) {largest = left;}if (right < heapSize && data[largest] < data[right]) {largest = right;}// 得到最大值後可能需要交換,如果交換了,其子節點可能就不是最大堆了,需要重新調整if (largest != index) {int temp = data[index];data[index] = data[largest];data[largest] = temp;maxHeapify(data, heapSize, largest);}}/** * 排序,最大值放在末尾,data雖然是最大堆,在排序後就成了遞增的 *  * @param data */private static void heapSort(int[] data) {// 末尾與頭交換,交換後調整最大堆for (int i = data.length - 1; i > 0; i--) {int temp = data[0];data[0] = data[i];data[i] = temp;maxHeapify(data, i, 0);}}/** * 父節點位置 *  * @param current * @return */private static int getParentIndex(int current) {return (current - 1) >> 1;}/** * 左子節點position 注意括弧,加法優先順序更高 *  * @param current * @return */private static int getChildLeftIndex(int current) {return (current << 1) + 1;}/** * 右子節點position *  * @param current * @return */private static int getChildRightIndex(int current) {return (current << 1) + 2;}private static void print(int[] data) {int pre = -2;for (int i = 0; i < data.length; i++) {if (pre < (int) getLog(i + 1)) {pre = (int) getLog(i + 1);System.out.println();}System.out.print(data[i] + " |");}}/** * 以2為底的對數 *  * @param param * @return */private static double getLog(double param) {return Math.log(param) / Math.log(2);}}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.