Advertisement
Guest User

Untitled

a guest
Oct 17th, 2018
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.95 KB | None | 0 0
  1. double min()
  2. {
  3. return heap[1];
  4. }
  5.  
  6. void insert(double value)
  7. {
  8. int child = ++heap_size;
  9. int parent = child / 2;
  10. while (parent && heap[parent] > value)
  11. {
  12. heap[child] = heap[parent];
  13. child = parent;
  14. parent /= 2;
  15. }
  16. heap[child] = value;
  17. }
  18. int min_child(int parent)
  19. {
  20. int left = 2 * parent;
  21. int right = left + 1;
  22. if (left > heap_size) return 0;
  23. if (right > heap_size || heap[left] < heap[right])
  24. return left;
  25. return right;
  26. }
  27.  
  28. void remove_min()
  29. {
  30. double last = heap[heap_size--];
  31. int x = 1;
  32. int c = katalog::min_child(1);
  33. while (c && heap[c] < last)
  34. {
  35. heap[x] = heap[c];
  36. x = c;
  37. c = katalog::min_child(c);
  38. }
  39. heap[x] = last;
  40. }
  41.  
  42. void heapsort(double array[], int size)
  43. {
  44. if (size > HEAP_MAX) return;
  45.  
  46. for (int i = 0; i < size; ++i)
  47. katalog::insert(array[i]);
  48.  
  49. for (int i = 0; i < size; ++i)
  50. {
  51. array[i] = min();
  52. katalog::remove_min();
  53. }
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement