#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <string>
using namespace std;
void print_list(int list[], int len) {
if (list == NULL || len <= 0) {
return;
}
int line = 0;
for (int i = 0; i < len; i++, line++) {
if (line > 9) {
cout << endl;
line = 0;
}
cout << list[i] << " ";
}
cout << endl;
}
template<class T>
void swap_value(T &a, T &b) {
T tmp = a;
a = b;
b = tmp;
}
/**
@pragma list 待調(diào)整數(shù)組
@pragma index 待調(diào)整節(jié)點下標
@pragma len 數(shù)組長度
*/
void HeapAdjust(int *list, int index, int len) {
// 先保存當前節(jié)點下標
int max = index;
// 保存左右子節(jié)點的數(shù)組下標
int left_child = index * 2 + 1;
int right_child = index * 2 + 2;
if (left_child < len && list[left_child] > list[max]) {
max = left_child;
}
if (right_child < len && list[right_child] > list[max]) {
max = right_child;
}
if (max != index) {
swap_value(list[max], list[index]);
HeapAdjust(list, max, len);
}
}
// 從小到大
void HeapSort(int list[], int len) {
if (list == NULL || len <= 0) {
return;
}
for (int i = len / 2 - 1; i >= 0; i--) {
HeapAdjust(list, i, len);
}
// 交換堆頂元素與最后一個元素
for (int i = len - 1; i >= 0; i--) {
swap_value(list[0], list[i]);
HeapAdjust(list, 0, i);
}
}
int main(int argc, char* argv[]) {
int list[] = {4, 2, 8, 0, 5, 7, 1, 3, 9};
int len = sizeof(list) / sizeof(*list);
print_list(list, len);
HeapSort(list, len);
print_list(list, len);
cout << endl;
return 0;
}
堆排序
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
- 文/潘曉璐 我一進店門丧枪,熙熙樓的掌柜王于貴愁眉苦臉地迎上來光涂,“玉大人,你說我怎么就攤上這事豪诲《ソ荩” “怎么了?”我有些...
- 文/不壞的土叔 我叫張陵屎篱,是天一觀的道長服赎。 經(jīng)常有香客問我,道長交播,這世上最難降的妖魔是什么重虑? 我笑而不...
- 正文 為了忘掉前任,我火速辦了婚禮秦士,結(jié)果婚禮上缺厉,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好提针,可當我...
- 文/花漫 我一把揭開白布命爬。 她就那樣靜靜地躺著,像睡著了一般辐脖。 火紅的嫁衣襯著肌膚如雪饲宛。 梳的紋絲不亂的頭發(fā)上,一...
- 文/蒼蘭香墨 我猛地睜開眼絮重,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了错妖?” 一聲冷哼從身側(cè)響起绿鸣,我...
- 正文 年R本政府宣布哩簿,位于F島的核電站宵蕉,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏节榜。R本人自食惡果不足惜羡玛,卻給世界環(huán)境...
- 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望宗苍。 院中可真熱鬧稼稿,春花似錦薄榛、人聲如沸。這莊子的主人今日做“春日...
- 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至是越,卻和暖如春耳舅,著一層夾襖步出監(jiān)牢的瞬間碌上,已是汗流浹背倚评。 一陣腳步聲響...
推薦閱讀更多精彩內(nèi)容
- 選擇排序 對于任何輸入猜丹,時間為O(n*n)芝加; 冒泡排序 最優(yōu)(對于升序的數(shù)組,因為加入了一個跳出判斷):O(n)射窒,...
- [前言] 此文章參考自《數(shù)據(jù)結(jié)構(gòu)(java版)》第三版藏杖,葉核亞 一、排序的基本概念: (1)性能評價:取決于時間復...