Advertisement
Guest User

Untitled

a guest
Oct 21st, 2019
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.78 KB | None | 0 0
  1. #include <iostream>
  2. using namespace std;
  3. void PrintArray(int* a, int n)
  4. {
  5. for (int i = 0; i < n; i++)
  6. cout << a[i] << " ";
  7. cout << "\n";
  8. }
  9. void TopDown(int* a, int n, int position, int* heap)
  10. {
  11. int parent = (position - 1) / 2;
  12. int x = position + 1;
  13. heap[position] = a[position];
  14. while (position > 0 && heap[position] > heap[parent])
  15. {
  16. //move parent down
  17. swap(heap[position], heap[parent]);
  18. /*if (heap[position] > heap[position-1]) swap(heap[position-1], heap[position]);
  19. position = parent;
  20. */
  21. parent = (position - 1) / 2;
  22. }
  23. PrintArray(heap, x);
  24. }
  25.  
  26. void TopDownDemo()
  27. {
  28. int a[6] = { 3,1,6,5,2,4 };
  29. int* heap = (int*)malloc(6* sizeof(int));
  30. for (int i = 0; i < 6; i++)
  31. TopDown(a, 6, i, heap);
  32. }
  33.  
  34. int main()
  35. {
  36. TopDownDemo();
  37. return 0;
  38. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement