frentzy

heapsort

Jan 14th, 2019
146
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.04 KB | None | 0 0
  1. #include <stdio.h>
  2.  
  3. #define NMAX 100000
  4.  
  5. int a[NMAX + 1];
  6. int n;
  7.  
  8.  
  9. void insert(int m) {
  10.   int i, j, aux;
  11.  
  12.   i = m;
  13.   j = i >> 1;
  14.   while ((j > 0) && (a[j] > a[i])) {
  15.     aux = a[j]; a[j] = a[i]; a[i] = aux;
  16.  
  17.     i = j;
  18.     j = i >> 1;
  19.   }
  20. }
  21.  
  22. void push(int m) {
  23.   int i, j, aux;
  24.  
  25.   i = 1;
  26.   j = i << 1;
  27.   while (j <= m) {
  28.     if ((j < m) && (a[j] > a[j + 1])) {
  29.       j++;
  30.     }
  31.  
  32.     if (a[i] > a[j]) {
  33.       aux = a[i]; a[i] = a[j]; a[j] = aux;
  34.  
  35.       i = j;
  36.       j = i << 1;
  37.     } else {
  38.         j = m + 1;
  39.     }
  40.   }
  41. }
  42.  
  43.  
  44. int main() {
  45.   FILE *fin, *fout;
  46.   int n, i, aux;
  47.  
  48.   fin = fopen("heapsort.in", "r");
  49.   fout = fopen("heapsort.out", "w");
  50.  
  51.   fscanf(fin, "%d", &n);
  52.   for (i = 1; i <= n; i++) {
  53.     fscanf(fin, "%d", &a[i]);
  54.   }
  55.  
  56.   for (i = 2; i <= n; i++) {
  57.     insert(i);
  58.   }
  59.  
  60.   for (i = n; i > 1; i--) {
  61.     aux = a[1]; a[1] = a[i]; a[i] = aux;
  62.  
  63.     push(i - 1);
  64.   }
  65.  
  66.   for (i = 1; i <= n; i++) {
  67.     fprintf(fout, "%d ", a[i]);
  68.   }
  69.  
  70.   fclose(fin);
  71.   fclose(fout);
  72.  
  73.   return 0;
  74. }
Add Comment
Please, Sign In to add comment