/**
* 對指定結點進行heapify的方法
* @param tree 堆的陣列
* @param i 對第幾個結點進行heapify
*/public
static
void
heapify
(int
tree,
int n,
int i)
int c1 =
2* i +1;
//根據指定結點 i 計算出孩子結點
int c2 =
2* i +2;
//同上
// 找出 i, c1, c2 中最大的放在父節點(就是heapify)
int max = i;
if(c1 < n -
1&& tree[c1]
> tree[max])if
(c1 < n -
1&& tree[c2]
> tree[max])if
(max != i)
}/**
* 對整個陣列進行建堆(從最後乙個父節點開始heapify)
* @param tree
*/public
static
void
buildheap
(int
tree)
}/**
* 建堆之後,交換根結點和最後乙個結點的位置,再對除最後乙個根結點對剩餘部分heapify
* @param tree
*/public
static
void
heapsort
(int
tree)
}@test
public
void
testheapify()
;heapsort
(tree)
;for
(int i =
0; i < tree.length; i++
)}
排序詳解 堆排序
堆排序 heapsort 是指利用堆積樹 堆 這種資料結構所設計的一種排序演算法,它是選擇排序的一種。可以利用陣列的特點快速定位指定索引的元素。堆分為大根堆和小根堆,是完全二叉樹。大根堆的要求是每個節點的值都不大於其父節點的值,即a parent i a i 在陣列的非降序排序中,需要使用的就是大根...
堆排序詳解
一 堆的定義 堆的定義如下 n個關鍵字序列l n 成為堆,當且僅當該序列滿足 l i l 2i 且l i l 2i 1 或者 l i l 2i 且l i l 2i 1 其中i屬於 1,n 2 滿足第 種情況的堆稱為小根堆 小頂堆 滿足第 種情況的堆稱為大根堆 大頂堆 在大根堆中,最大元素存放在根結點...
堆排序詳解
public class heapsort 此時已經完成了最大堆的構建,下面進行排序。for int i len 1 i 0 i 維護最大堆,保證父節點大於等於子節點 public static void maxheapify int a,int index,int len if rightchil...