#include<iostream>
#include<vector>
#include<string>
#include<set>
#include<map>
#include<unordered_set>
#include<unordered_map>
#include<algorithm>
#include<xfunctional>
using namespace std;
typedef struct heap{
int arr_size;
int heap_size;
int *arr;
}heap;
void Tune(heap& h,int start){
int i = start;
while (2 * i < h.heap_size){
int index = i;
int max_temp = h.arr[index];
if (h.arr[2 * i]>max_temp){
index = 2 * i;
max_temp = h.arr[index];
}
if (2 * i + 1 <= h.heap_size){
if (h.arr[2 * i + 1] > max_temp){
index = 2 * i + 1;
max_temp = h.arr[index];
}
}
if (index == i) return;
else{
swap(h.arr[index],h.arr[i]);
i = index;
}
}
}
void BuildHeap(heap &h){
for (int i = h.heap_size / 2; i >0; i--){
Tune(h,i);
}
}
void heap_sort(heap &h){
for (int i = h.heap_size; i > 1; i--){
swap(h.arr[1], h.arr[h.heap_size]);
h.heap_size--;
Tune(h,1);
}
}
int main(){
heap h;
cout << "Input the size of the array:";
cin >> h.arr_size;
h.arr = new int[h.arr_size+1];
h.heap_size = h.arr_size;
cout << "Input the element:";
for (int i = 1; i <= h.arr_size; i++) cin >> h.arr[i];
BuildHeap(h);
cout << "After build:";
for (int i = 1; i <= h.arr_size; i++) cout << h.arr[i] << " ";
cout << endl;
heap_sort(h);
cout << "After sort:";
for (int i = 1; i <= h.arr_size; i++) cout << h.arr[i]<<" ";
cout << endl;
system("pause");
return 0;
}
算法导论(build the heap iteratively 迭代建堆)
最新推荐文章于 2024-09-10 11:06:15 发布