堆的创建 插入和删除

바빠 바빠 바빠~
///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.

****/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值