知識のポイント
ヒープ:完全な二分木。
ラージルートヒープ:ルートノードを除くすべてのノード、ノードの値は親ノード以下;
スモールルートヒープ:ルートノードを除くすべてのノード、ノードの値は親以上ノード;
ヒープソート:O(nlogn)、O(1)、不安定;
完全な二分木:各ノードは次数2のリーフノードまたは
完全な二分木です:深さがkでノードの数が2 ^ k-1の
二分木です。完全な二分木:ノードの数はに対応します完全な二分木の数。
関数の説明
- heapify:現在のノードのサブツリーが最大ヒープまたは最小ヒープの定義を満たすようにします
- スワップ:スワップ
- build_heap:ヒープを構築します。最初の非リーフノードから開始し、徐々に上に移動します。つまり、移動した各ノードはheapify関数を呼び出します。
- heap_sort:ヒープソート(ビッグルートヒープ)を実現し、ルートノード(index = 0)を最後のノードと交換させます。この時点では、ビッグルートヒープが満たされていないため、最後のノード(つまり最大値)が満たされていません。が切断され、ルートが再実行されますHeapify
function swap(tree, i, j){
let temp = tree[i];
tree[i] = tree[j];
tree[j] = temp;
}
function heapify(tree, n, i){
if (i >= n) return;
let left = i*2 + 1;
let right = i*2 + 2;
let max = i;
if (left < n && tree[left] > tree[max]){
max = left;
}
if (right < n && tree[right] > tree[max]){
max = right;
}
if (max !== i){
swap(tree, max, i);
heapify(tree, n, max);
}
}
function build_heap(tree, n){
let last_node = n-1;
let parent = Math.floor((last_node - 1) / 2); // 注意向下取整
for (let i = parent; i >= 0; i--){
heapify(tree, n, i);
}
}
function heap_sort(tree, n){
build_heap(tree, n);
for (let i=n-1; i>=0; i--){
swap(tree, 0, i);
heapify(tree, i, 0);
}
}
let tree = [2,4,6,3,10,1,5];
heap_sort(tree, 7);
console.log(tree);
#include <iostream>
using namespace std;
void swap(int tree[], int i, int j){
int temp = tree[i];
tree[i] = tree[j];
tree[j] = temp;
}
// 最大堆就是一个完全二叉树
// 当前节点i(i表示下标)的parent的index: (i-1)/2
// 当前节点i的left-child的index:i*2 + 1
// 当前节点i的right-child的index:i*2 + 2
void heapify(int tree[], int n, int i){
// heapify就是从某个节点出发,让这个节点满足最大堆的定义
if (i >= n) return;
// n表示数组的长度,i表示当前的第几个元素
int c1 = i*2 + 1;
int c2 = i*2 + 2;
int max = i;
if (c1 < n && tree[c1] > tree[max]){
max = c1;
}
if (c2 < n && tree[c2] > tree[max]){
max = c2;
}
if (max != i){
swap(tree, i, max); // 说明存在比tree[i]大的值
heapify(tree, n, max);
}
}
void build_heap(int tree[], int n){
// 建立大根堆
// 从第一个非叶子结点开始做heapify
int last_node = n-1;
int parent = (last_node - 1) / 2;
for (int i=parent; i>=0; i--){
heapify(tree, n, i);
}
}
void heap_sort(int tree[], int n){
build_heap(tree, n);
for (int i=n-1; i>=0; i--){
swap(tree, i, 0);
// 将第一个节点,也就是最大值与最后一个元素交换,然后把最后一个元素“砍断”,不进行heapify
heapify(tree, i, 0); // O(logi)
}
}
int main(){
int tree[] = {
2,4,6,3,10,1,5};
// heapify(tree, 7, 0);
heap_sort(tree, 7);
for(int i=0; i<7; i++){
cout << tree[i] << " ";
}
cout << endl;
return 0;
}