Advertisement
mIs4

Untitled

Dec 4th, 2022
529
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.91 KB | None | 0 0
  1.        public static void HeapSort(int[] input, bool maxHeap = false)
  2.         {
  3.             BuildHeap(input, maxHeap);
  4.             int inputSize = input.Length;
  5.             for (int i = input.Length-1; i>=1; i--)
  6.             {
  7.                 int tmp = input[i];
  8.                 input[i] = input[0];
  9.                 input[0] = tmp;
  10.                 inputSize--;
  11.                 Heapify(input, inputSize, 0, maxHeap);
  12.             }
  13.         }
  14.  
  15.  
  16.  
  17.         public static void Heapify(int[] heap, int heapSize, int i, bool maxHeap = false)
  18.         {
  19.             if (maxHeap)
  20.             {
  21.                 int l = 2 * i;
  22.                 int r = 2 *i + 1;
  23.                 int max = i;
  24.                 if (l < heapSize && heap[l] > heap[i])
  25.                     max = l;
  26.                 if (r < heapSize && heap[r] > heap[max])
  27.                     max = r;
  28.                 if (max != i)
  29.                 {
  30.                     int tmp = heap[i];
  31.                     heap[i] = heap[max];
  32.                     heap[max] = tmp;
  33.                     Heapify(heap, heapSize, max, maxHeap);
  34.                 }
  35.             }
  36.             else
  37.             {
  38.                 int l = 2*i;
  39.                 int r = 2*i+1;
  40.                 int min = i;
  41.                 if (l < heapSize && heap[l] < heap[i])
  42.                     min = l;
  43.                 if (r < heapSize && heap[r] < heap[min])
  44.                     min = r;
  45.                 if (min != i)
  46.                 {
  47.                     int tmp = heap[i];
  48.                     heap[i] = heap[min];
  49.                     heap[min] = tmp;
  50.                     Heapify(heap, heapSize, min, maxHeap);
  51.                 }
  52.             }
  53.         }
  54.  
  55.         public static void BuildHeap(int[] list, bool maxHeap = false)
  56.         {
  57.             for (int i = list.Length/2; i >= 0; i--)
  58.             {
  59.                 Heapify(list, list.Length, i, maxHeap);
  60.             }
  61.         }
  62.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement