Advertisement
loulett

HW2_merge_sort

Nov 24th, 2014
175
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.43 KB | None | 0 0
  1. #include <cstdio>
  2. #include <cstdlib>
  3. #define _CRT_SECURE_NO_WARNINGS
  4.  
  5. void swap(int i, int j, int * heap)
  6. {
  7.     int t = 0;
  8.     t = heap[i];
  9.     heap[i] = heap[j];
  10.     heap[j] = t;
  11.     return;
  12. }
  13.  
  14. void sift_up(int n, int *heap)
  15. {
  16.     int i = n;
  17.     while (i > 0)
  18.     {
  19.         if (heap[i] <= heap[(i - 1) / 2])
  20.             return;
  21.         swap(i, (i - 1) / 2, heap);
  22.         i = (i - 1) / 2;
  23.     }
  24.     return;
  25. }
  26.  
  27. void sift_down(int n, int *heap)
  28. {
  29.     int i = 0;
  30.     while (i < n - 1)
  31.     {
  32.         if (heap[i] >= heap[2 * i + 2] && heap[i] >= heap[2 * i + 1])
  33.             return;
  34.         else if (heap[i] < heap[2 * i + 2] && heap[2 * i + 2]>heap[2 * i + 1])
  35.         {
  36.             swap(2 * i + 2, i, heap);
  37.             i = 2 * i + 2;
  38.         }
  39.         else
  40.         {
  41.             swap(2 * i + 1, i, heap);
  42.             i = 2 * i + 1;
  43.         }
  44.     }
  45. }
  46.  
  47. int * create_heap(int n, int * arr)
  48. {
  49.  
  50.     int * heap = (int *)malloc(n * sizeof(int));
  51.     heap[0] = arr[0];
  52.     for (int i = 1; i < n; i++)
  53.     {
  54.         heap[i] = arr[i];
  55.         sift_up(i, heap);
  56.     }
  57.     return heap;
  58. }
  59.  
  60. int del_max(int n, int * heap)
  61. {
  62.     swap(0, n - 1, heap);
  63.     int t = heap[n - 1];
  64.     heap[n - 1] = 0;
  65.     n--;
  66.     sift_down(n, heap);
  67.     return t;
  68. }
  69.  
  70. int main()
  71. {
  72.     int n = 0, t = 0;
  73.     scanf("%d", &n);
  74.     int * arr = (int*)malloc(n*sizeof(int));
  75.     for (int i = 0; i < n; ++i)
  76.         scanf("%d", &arr[i]);
  77.     int *heap = create_heap(n, arr);
  78.     for (int i = 0; i < n; i++)
  79.         printf("%d ", heap[i]);
  80.     printf("\n");
  81.     printf("%d\n", del_max(n, heap));
  82.     for (int i = 0; i < n; i++)
  83.         printf("%d ", heap[i]);
  84.     return 0;
  85. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement