未经验证的堆 C 代码,求验证

来源:互联网 发布:md5加解密网站源码php 编辑:程序博客网 时间:2024/06/05 05:14

rt

#include <stdio.h>#include <stdlib.h>int len;int heap[20];void swap(int *a,int *b){     int tmp=*a;     *a=*b;     *b=tmp;}void push_heap(int *heap,int s){     heap[++len]=s;     int t=len;     while (t>1)     {           if (heap[t>>1]>heap[t])           {              swap(&heap[t>>1],&heap[t]);           }           else return;     }}int pop_heap(int *heap){     int re=heap[1],x;     heap[1]=heap[len--];     int m=len>>1,t=1,k;     while (t<=m)     {        k=t;        if (heap[t<<1]<heap[t])           k=t<<1;        if ((t<<1)+1<=len)           if(heap[k]>heap[(t<<1)+1])              k=(t<<1)+1;             if (k!=t)        {           x=heap[k];           heap[k]=heap[t];           heap[t]=x;           t=k;        }        else return re;     }     return re;}void heap_adjust(int *heap,int pos,int end){     int i;     int t=heap[pos];     for (i=2*pos;i<=end;i<<=1)     {         if (i<end && heap[i]<heap[i+1])            ++i;         if (heap[pos]>heap[i]) break;         heap[pos]=heap[i];         pos=i;     }     heap[pos]=t;}void sort_heap(int *heap){     int i;     int t;     for (i=len/2;i>0;i--)         heap_adjust(heap,i,len);     for (i=len;i>1;i--)     {         swap(&heap[1],&heap[i]);         heap_adjust(heap,1,i-1);     }}int main(){    scanf("%d",&len);    int i;    for (i=1;i<=len;++i)        scanf("%d",&heap[i]);    sort_heap(heap);    push_heap(heap,9);    while (len>0) printf("%d\n",pop_heap(heap));    system("pause");}


 

原创粉丝点击