2019-11-14  本文已影响0人  雨落夏至

遍历堆从根到叶结点
void dfs(int d)
{
    if(2 * d > n){ //不再往下搜索
        if(d <= n){
            for(int i = 0; i < path.size(); ++i){
                if(i != path.size() - 1)
                    printf("%d ",path[i]);
                else printf("%d\n",path[i]);
            }
        }
        return;
    }
    //先走右子树
    path.push_back(keys[2 * d + 1]);
    dfs(2 * d + 1);
    path.pop_back();//回溯
    //再走左子树
    path.push_back(keys[2 * d]);
    dfs(2 * d);
    path.pop_back();//回溯
}
判断最大堆最小堆
for(int i = 2; i <= n; ++i){
       if(keys[i / 2] > keys[i]) isMin = 0;
       if(keys[i / 2] < keys[i]) isMax = 0;
    }

堆排序

基本思想:

以前老是以为要递归。。。。
嗷嗷嗷,静下心写写原始堆排序也挺简单的hhh(开始做梦,然后被吊打

#include<iostream>

using namespace std;
int n;

void swap(int a,int b,int heap[]){
    int temp;
    temp=heap[a];
    heap[a]=heap[b];
    heap[b]=temp;
}

void createHeap(int heap[],int size){
    int i=size;
    while(i/2>=1){
        if(heap[i/2]<heap[i]){
            swap(i/2,i,heap);
        }
        i=i/2;
    }
}

int main(){

    cin>>n;
    int heap[1001]={0};
    for(int i=1;i<=n;i++){
        cin>>heap[i];
        createHeap(heap,i);
    }
    for(int i=1;i<=n;i++){
        cout<<heap[i]<<" ";
    }
    cout<<endl;
    for(int i=n;i>=1;i--){
        swap(1,i,heap);
        cout<<heap[i]<<" ";
        int start=1;
        while(start*2<=i-1){
            if(heap[start]<heap[start*2]){
                if(start*2+1>i-1||heap[start*2]>heap[start*2+1]){
                    swap(start*2,start,heap);
                    start=start*2;

                }
                else{
                    swap(2*start+1,start,heap);
                    start=start*2+1;
                }
            }
            else{
                if(start*2+1<=i-1&&heap[start]<heap[start*2+1]){
                    swap(start*2+1,start,heap);
                    start=start*2+1;
                }
                else break;
            }
//            cout<<"+"<<heap[start]<<"--"<<start<<endl;
        }
    }
    return 0;
}
上一篇 下一篇

猜你喜欢

热点阅读