试设计一个算法,判断一个数据序列是否构成一个小根堆(下面代码中的堆排序的部分仅仅是为了方便设计测试用例)
#include <iostream>
#include<time.h>
#include<stdlib.h>int * buildarray(int size)
{int* tmp=(int *) malloc(sizeof(int)*size);for(int i=0;i<size;i++) tmp[i]=rand()%20;return tmp;
}void print(int * tmp,int size)
{for(int i=0;i<size;i++)printf("%3d",tmp[i]);puts("");
}void down(int * tmp,int size,int k)
{int record=tmp[k];for(int i=k*2+1;i<size;i=2*i+1){if(i+1<size&&tmp[i]>tmp[i+1]) i++;if(tmp[i]>=record) break;else tmp[k]=tmp[i],k=i;}tmp[k]=record;
}
void adjust(int * tmp,int size)
{for(int i=size/2-1;i>=0;i--)down(tmp,size,i);
}
bool small_heap(int *tmp,int size)
{for(int i=size/2-1;i>=0;i--){if(tmp[i*2+1]<tmp[i]) return false;if(i*2+2<size&&tmp[i*2+2]<tmp[i]) return false;}return true;
}
int main() {int size=15;srand(time(nullptr));int *a1= buildarray(size);printf("a1:");print(a1,size);adjust(a1,size);print(a1,size);//a1是一个经过了向下调整的数组,是一个小根堆if(small_heap(a1,size)) printf("this is a min rooted heap\n");else printf("this is not a min rooted heap\n");int a2[]={1,2,5,4,4,9,11,16,3,8,10,16,9,14};//这里的元素3是导致这不是一个小根堆的原因;printf("a2:");print(a2,14);if(small_heap(a2,14)) printf("this is a min rooted heap\n");else printf("this is not a min rooted heap\n");return 0;
}