Advertisement
Guest User

Untitled

a guest
Dec 12th, 2018
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.20 KB | None | 0 0
  1. #define PQ_SIZE 1000
  2. typedef int item_type;
  3.  
  4. struct priority_queue {
  5. item_type q[PQ_SIZE + 1];
  6. int n;
  7. };
  8.  
  9. int pq_parent(int n)
  10. {
  11. if(n == 1)
  12. return -1;
  13. else
  14. return n / 2;
  15. }
  16.  
  17. int pq_young_child(int n)
  18. {
  19. return 2 * n;
  20. }
  21.  
  22. void pq_swap(struct priority_queue *q, int a, int b)
  23. {
  24. int c = q->q[a];
  25. q->q[a] = q->q[b];
  26. q->q[b] = c;
  27. }
  28.  
  29. void bubble_up(struct priority_queue *q, int p)
  30. {
  31. if(pq_parent(p) == -1) /* at root of heap, no parent */
  32. return;
  33. if(q->q[pq_parent(p)] > q->q[p]) {
  34. pq_swap(q, p, pq_parent(p));
  35. bubble_up(q, pq_parent(p));
  36. }
  37. }
  38.  
  39.  
  40. void pq_insert(struct priority_queue *q, item_type x)
  41. {
  42. if (q->n >= PQ_SIZE)
  43. printf("Warning: priority queue overflow insert x=%d\n", x);
  44. else {
  45. q->n = (q->n) + 1;
  46. q->q[q->n] = x;
  47. bubble_up(q, q->n);
  48. }
  49. }
  50.  
  51. void pq_init(struct priority_queue *q)
  52. {
  53. q->n = 0;
  54. }
  55.  
  56. void make_heap(struct priority_queue *q, item_type s[], int n)
  57. {
  58.  
  59. pq_init(q);
  60. for(int i = 0; i < n; ++i)
  61. pq_insert(q, s[i]);
  62. }
  63.  
  64. void bubble_down(struct priority_queue *q, int p)
  65. {
  66. int c; /* child index */
  67. int i; /* counter */
  68. int min_index; /* index of lightest child */
  69.  
  70. c = pq_young_child(p);
  71. min_index = p;
  72.  
  73. for(i = 0; i <= 1; ++i)
  74. if ((c + i) <= q->n)
  75. if(q->q[min_index] > q->q[c + i])
  76. min_index = c + i;
  77.  
  78. if (min_index != p) {
  79. pq_swap(q, p, min_index);
  80. bubble_down(q, min_index);
  81. }
  82. }
  83.  
  84. item_type extract_min(struct priority_queue *q)
  85. {
  86. int min; /* minimum value */
  87.  
  88. if (q->n <= 0)
  89. printf("Warning: empty priority queue.\n");
  90. else {
  91. min = q->q[1];
  92.  
  93. q->q[1] = q->q[q->n];
  94. --q->n;
  95. bubble_down(q,1);
  96. }
  97.  
  98. return min;
  99. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement