fork download
  1. #include<iostream>
  2. using namespace std;
  3.  
  4. void heapify_delete(int a[], int n, int i){
  5. int left = 2*i + 1;
  6. int right = 2*i + 2;
  7. int largest = i;
  8.  
  9. if(a[left] > a[largest] && left < n){
  10. largest = left;
  11. }
  12. if(a[right] > a[largest] && right < n){
  13. largest = right;
  14. }
  15.  
  16. if(largest != i){
  17. swap(a[largest], a[i]);
  18. heapify_delete(a, n, largest);
  19. }
  20. }
  21.  
  22. void heapify_insert(int a[], int n, int i){
  23. int parent = (i-1)/2;
  24.  
  25. if(a[i] > a[parent]){
  26. swap(a[i], a[parent]);
  27. heapify_insert(a, n, parent);
  28. }
  29. }
  30.  
  31. void insert(int a[], int &n, int key){
  32. n = n+1;
  33. a[n-1] = key;
  34. heapify_insert(a, n, n-1);
  35. }
  36.  
  37. void del(int a[], int &n){
  38. a[0] = a[n-1];
  39. n--;
  40. heapify_delete(a, n, 0);
  41. }
  42.  
  43. void print(int a[], int n){
  44. for(int i = 0; i < n; i++) cout << a[i] << " ";
  45. cout << endl;
  46. }
  47.  
  48. int main(){
  49. int n,i;
  50. clock_t time_req;
  51. time_req=clock();
  52. cout << "enter size of the array" << endl;
  53. cin >> n;
  54. int a[n];
  55. cout<< "enter elements" << endl;
  56. for(i = 0; i < n; i++) cin >> a[i];
  57.  
  58. insert(a, n, 15);
  59. print(a, n);
  60. del(a, n);
  61. print(a, n);
  62.  
  63. //cout<< "the sorted array is" <<endl;
  64.  
  65. // for(m=0;m<n;m++)
  66. // cout<<a[m]<<" ";
  67. // cout<<endl;
  68.  
  69. time_req=clock()-time_req;
  70. cout<<"the time taken is"<<endl;
  71. cout<<(float)time_req/CLOCKS_PER_SEC<<"seconds"<<endl;
  72.  
  73. cout<<"The bytes occupied is"<<endl;
  74. cout<<(sizeof(a[n])*n)+sizeof(n)+sizeof(i);
  75. }
Success #stdin #stdout 0.01s 5392KB
stdin
5
10 5 3 2 4
stdout
enter size of the array
enter elements
15 5 10 2 4 3 
10 5 3 2 4 
the time taken is
4.7e-05seconds
The bytes occupied is
28