바빠 바빠 바빠~
///heap
#include<iostream>
using namespace std;
void heap_insert(int *heap, int i, int num){
int j = (i-1)>>1;
heap[i] = num;
while(j>=0 && i!=0){
if(heap[j] < num)
break;
heap[i] = heap[j];
i = j;
j = (i-1)>>1;
}
heap[i] = num;
}
void heap_adjust(int *heap, int top, int n){
int j = 2*top+1;
int temp = heap[top];
while(j<n){
if(j+1<n && heap[j+1]<heap[j])
j++;
if(heap[j]>=temp)
break;
heap[top] = heap[j];
top = j;
j = 2*top+1;
}
heap[top] = temp;
}
void heap_delete(int *heap, int n){
heap[0] = heap[n-1];
heap_adjust(heap, 0, n-1);
}
void heap_create(int *heap, int n){
for(int i=(n-2)/2; i>=0; i--){
heap_adjust(heap, i, n);
}
}
void heap_sort(int *heap, int n){
for(int i=n-1; i>=0; i--){
int temp = heap[i];
heap[i] = heap[0];
heap[0] = temp;
heap_adjust(heap, 0, i);
}
}
int main(){
int heap[100];
int n;
cin >> n;
///对给出的一棵完全二叉树 进行自底向上的堆调整 建小顶堆
cout << "Create1: " ;
for(int i=0; i<n; i++){
cin >> heap[i];
}
heap_create(heap, n);
for(int i=0; i<n; i++){
cout << heap[i] << ' ';
}
cout << endl;
cout << "Create2: ";
///动态插入 小顶堆
for(int i=0; i<n; i++){
cin >> heap[i];
heap_insert(heap, i, heap[i]);///shift_up
}
for(int i=0; i<n; i++){
cout << heap[i] << ' ';
}
cout << endl;
cout << "heap_delete: ";
heap_delete(heap, n);
for(int i=0; i<n-1; i++){
cout << heap[i] << ' ';
}
cout << endl;
cout << "heap_sort: ";
heap_sort(heap, n-1);
for(int i=0; i<n-1; i++){
cout << heap[i] << ' ';
}
return 0;
}
/****
6
Create1: 9 3 2 1 8 7
1 3 2 9 8 7
Create2: 9 3 2 1 8 7
1 2 3 9 8 7
heap_delete: 2 7 3 9 8
heap_sort: 9 8 7 3 2
Process returned 0 (0x0) execution time : 61.704 s
Press any key to continue.
****/
堆的创建 插入和删除
最新推荐文章于 2022-04-08 18:22:12 发布