SuperMonkey

heap.c

Jun 15th, 2015
357
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.67 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <assert.h>
  4. #include <time.h>
  5. #include <string.h>
  6.  
  7. typedef struct {
  8.     int* tab;
  9.     int nb;
  10. } heap_t;
  11.  
  12. heap_t* heap_create(size_t n);
  13. void    heap_insert(heap_t* h, int v);
  14. int     heap_getAndRemoveMin(heap_t* h);
  15. int     heap_getMin(heap_t* h);
  16. void    heap_free(heap_t* h);
  17.  
  18. void swap(int* a, int *b) {
  19.     register int tmp=*a;
  20.     *a=*b;
  21.     *b=tmp;
  22. }
  23.  
  24. heap_t* heap_create(size_t n) {
  25.     heap_t* h = (heap_t*) malloc(sizeof(heap_t));
  26.     assert(h);
  27.     h->nb = 0;
  28.     h->tab = (int*) malloc(sizeof(int)*n);
  29.  
  30.     return h;
  31. }
  32.  
  33. void heap_free(heap_t* h) {
  34.     free(h->tab);
  35.     free(h);
  36. }
  37.  
  38. void heap_insert(heap_t* h, int v) {
  39.     assert(h);
  40.  
  41.     int pos = ++(h->nb);
  42.  
  43.     h->tab[pos] = v;
  44.     while(pos != 1 && h->tab[pos/2] > h->tab[pos]) {
  45.         swap(&h->tab[pos/2], &h->tab[pos]);
  46.         pos/=2;
  47.     }
  48. }
  49.  
  50. int __min_child_pos(heap_t* h, int x) {
  51.     if(x*2+1>h->nb || h->tab[x*2+1]>h->tab[x*2]) return x*2;
  52.     return x*2+1;
  53. }
  54.  
  55. int heap_getAndRemoveMin(heap_t* h) {
  56.     assert(h);
  57.  
  58.     int ret = h->tab[1];
  59.     h->tab[1] = h->tab[h->nb--];
  60.  
  61.     int pos=1,mcp;
  62.     while(pos*2 <= h->nb && h->tab[(mcp=__min_child_pos(h, pos))] < h->tab[pos]) {
  63.         swap(&h->tab[mcp], &h->tab[pos]);
  64.         pos=mcp;
  65.     }
  66.  
  67.     return ret;
  68. }
  69.  
  70. int main(int argc, char const *argv[]) {
  71.     heap_t* h = heap_create(300);
  72.  
  73.     srand(time(0));
  74.  
  75.     char done[200];
  76.     int alea;
  77.     memset(done, 0, 200);
  78.     for(int i=0;i<200;i++) {
  79.         alea = rand()%200;
  80.         if(!done[alea]) {
  81.             heap_insert(h, alea);
  82.             printf("insert %d\n", alea);
  83.             done[alea]=1;
  84.         }
  85.     }
  86.  
  87.     printf("NB : %d\n", )
  88.  
  89.     // for(int i=0; i<h->nb; i++) {
  90.     //  printf("%d\n",heap_getAndRemoveMin(h));
  91.     // }
  92.     puts("");
  93.  
  94.     heap_free(h);
  95.  
  96.     return 0;
  97. }
Advertisement
Add Comment
Please, Sign In to add comment