fork download
  1. #include <stdio.h>
  2. #define FIN "algsort.in"
  3. #define FOUT "algsort.out"
  4. #define DIM 500005
  5.  
  6. int Heap[ DIM ],
  7.  
  8. sizeH;
  9.  
  10. void up( int child ) {
  11.  
  12. int parent = child / 2;
  13.  
  14. while( parent ) {
  15.  
  16. if(Heap[parent] > Heap[child]) {
  17.  
  18. int aux = Heap[parent];
  19.  
  20. Heap[parent] = Heap[child];
  21.  
  22. Heap[child] = aux;
  23.  
  24. child = parent;
  25.  
  26. parent = child / 2;
  27.  
  28. } else break;
  29. }
  30. }
  31.  
  32. void down( int parent ) {
  33.  
  34. while(2 * parent <= sizeH) {
  35.  
  36. int child = 2 * parent;
  37.  
  38. if(2 * parent + 1 <= sizeH && Heap[2 * parent + 1] < Heap[2 * parent]) child++;
  39.  
  40. if(Heap[parent]<=Heap[child]) break;
  41.  
  42. int aux = Heap[parent];
  43. Heap[parent] = Heap[child];
  44. Heap[child] = aux;
  45.  
  46. parent = child;
  47. }
  48.  
  49. }
  50.  
  51. void insertHeap(int value) {
  52.  
  53. Heap[ ++sizeH ] = value;
  54.  
  55. up( sizeH );
  56. }
  57.  
  58. int removeHeap() {
  59.  
  60. int ret = Heap[ 1 ];
  61.  
  62. Heap[ 1 ] = Heap[ sizeH-- ];
  63.  
  64. down( 1 );
  65.  
  66. return ret;
  67. }
  68.  
  69. int main(int argc, char const *argv[]) {
  70.  
  71. int N,
  72. val;
  73.  
  74. //freopen(FIN, "r", stdin);
  75.  
  76. //freopen(FOUT, "w", stdout);
  77.  
  78. scanf("%d", &N);
  79.  
  80. for(int i = 1; i <= N; ++i) {
  81.  
  82. scanf("%d", &val);
  83.  
  84. insertHeap(val);
  85. }
  86.  
  87. for(int i = 1; i <= N; ++i) printf("%d ", removeHeap());
  88.  
  89. return 0;
  90. }
  91.  
Success #stdin #stdout 0s 5656KB
stdin
10
9 8 -7 6 5 -1 3 2 11 0
stdout
-7 -1 0 2 3 5 6 8 9 11