fork download
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3.  
  4.  
  5. void insert(int x, vector<int>& min_heap, int &top){
  6. min_heap.push_back(x);
  7. top++;
  8. int index = top;
  9. while(index > 0){
  10. int parent = (index - 1) / 2; // fixed
  11. if(min_heap[parent] > min_heap[index]){
  12. swap(min_heap[parent], min_heap[index]);
  13. index = parent;
  14. } else {
  15. break;
  16. }
  17. }
  18. }
  19.  
  20.  
  21. void delete_heap(vector<int>& min_heap,int &top){
  22. if(top==-1) return;
  23. min_heap[0]=min_heap[top];
  24. min_heap.pop_back();
  25. top--;
  26. int index=0;
  27. while(index<=top){
  28. int left=2*index+1;
  29. int right=2*index+2;
  30. int smallest=index;
  31. if(left<=top && min_heap[left]<min_heap[smallest]){
  32. smallest=left;
  33. }
  34. if(right<=top && min_heap[right]<min_heap[smallest]){
  35. smallest=right;
  36. }
  37. if(smallest!=index){
  38. swap(min_heap[smallest],min_heap[index]);
  39. index=smallest;
  40. } else {
  41. break;
  42. }
  43. }
  44.  
  45. }
  46.  
  47. int main(){
  48. vector<int> min_heap;
  49. int top=-1;
  50.  
  51. for(int i=0;i<5;i++){
  52. int x;
  53. cin>>x;
  54. insert(x,min_heap,top);
  55. }
  56. cout << "Heap after insertion: ";
  57. for(int i=0;i<=top;i++){
  58. cout << min_heap[i] << " ";
  59. }
  60. return 0;
  61.  
  62. }
Success #stdin #stdout 0.01s 5288KB
stdin
Standard input is empty
stdout
Heap after insertion: 0 0 0 0 0