java 堆排序 實現

來源:互聯網
上載者:User

標籤:堆排序



堆排序啊,其實是一種資料結構,二叉樹,二叉樹分為是滿二叉樹和完全二叉樹。一棵深度為 k,且有 2k - 1 個節點稱之為滿二叉樹,完全二叉樹:深度為 k,有 n 個節點的二叉樹,若且唯若其每一個節點都與深度為 k 的滿二叉樹中序號為 1 至 n 的節點對應時,稱之為完全二叉樹。

話收回來,堆呢,有最大堆,最小堆,最大堆是子節點沒有比父節點小的,最小堆則相反。下面是堆排序,可以自己畫一個草圖自己畫畫,堆排序的過程。


package com.test1;


//堆排序

public class HeapSortFinal {


public static void main(String[] args) {

int[] array = { 19, 38, 7, 36, 5, 5, 3, 2, 1, 0, 56 };


System.out.println("排序前:");

for (int i = 0; i < array.length; i++) {

System.out.print(array[i] + ",");

}


System.out.println();

System.out.println("分割線---------------");


heapSort(array);


System.out.println("排序後:");

for (int i = 0; i < array.length; i++) {

System.out.print(array[i] + ",");

}

}


public static void heapSort(int[] array) {

if (array == null || array.length == 1)

return;


buildMaxHeap(array); // 第一次排序,構建最大堆,只保證了堆頂元素是數組裡最大的


for (int i = array.length - 1; i >= 1; i--) {

// 這個是什麼意思呢?,經過上面的一些列操作,目前array[0]是當前數組裡最大的元素,需要和末尾的元素交換

// 然後,拿出最大的元素

swap(array, 0, i);


// 交換完後,下次遍曆的時候,就應該跳過最後一個元素,也就是最大的那個值,然後開始重新構建最大堆

// 堆的大小就減去1,然後從0的位置開始最大堆

maxHeap(array, i, 0);

}

}


// 構建堆

public static void buildMaxHeap(int[] array) {

if (array == null || array.length == 1)

return;


// 堆的公式就是 int root = 2*i, int left = 2*i+1, int right = 2*i+2;

int cursor = array.length / 2;

for (int i = cursor; i >= 0; i--) { // 這樣for迴圈下,就可以第一次排序完成

maxHeap(array, array.length, i);

}

}


// 最大堆

public static void maxHeap(int[] array, int heapSieze, int index) {

int left = index * 2 + 1; // 左子節點

int right = index * 2 + 2; // 右子節點

int maxValue = index; // 暫時定在Index的位置就是最大值


// 如果左子節點的值,比當前最大的值大,就把最大值的位置換成左子節點的位置

if (left < heapSieze && array[left] > array[maxValue]) {

maxValue = left;

}


// 如果右子節點的值,比當前最大的值大,就把最大值的位置換成右子節點的位置

if (right < heapSieze && array[right] > array[maxValue]) {

maxValue = right;

}


// 如果不相等,說明啊,這個子節點的值有比自己大的,位置發生了交換了位置

if (maxValue != index) {

swap(array, index, maxValue); // 就要交換位置元素


// 交換完位置後還需要判斷子節點是否打破了最大堆的性質。最大堆性質:兩個子節點都比父節點小。

maxHeap(array, heapSieze, maxValue);

}

}


// 數組元素交換

public static void swap(int[] array, int index1, int index2) {

int temp = array[index1];

array[index1] = array[index2];

array[index2] = temp;

}


}


本文出自 “10093778” 部落格,請務必保留此出處http://10103778.blog.51cto.com/10093778/1915183

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.