Advertisement
GrandtherAzaMarks

Heap (Heap Sort)

Apr 7th, 2018
130
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.95 KB | None | 0 0
  1. using System;
  2. using System.Linq;
  3. using System.Collections;
  4. using System.Collections.Generic;
  5.  
  6. ////////======================================================////////
  7. class MainClass
  8. {
  9.   static int BiggerIndx(int[] V, int a, int b)
  10.   {
  11.     if (a > b) return a;
  12.     else return b;
  13.   }
  14. ////////surprizly swaps elements
  15. ////////------------------------------------------------------////////
  16.   static void Swap(ref int a, ref int b)
  17.   {
  18.     int t = a;
  19.     a = b;
  20.     b = t;
  21.   }
  22. ////////Heap (out reapair)
  23. ////////------------------------------------------------------////////
  24.   static void repair(ref int[] V, int p, int top)
  25.   {
  26.     int l = 2 * p + 1;
  27.     int r = 2 * p + 2;
  28.     if (top <= l) return;
  29.     if (top == l + 1) r = l;
  30.     int imax = V[l] > V[r] ? l : r;
  31.     if (V[imax] > V[p])
  32.       Swap(ref V[imax], ref V[p]);
  33.     repair(ref V, imax, top);
  34.   }
  35. ////////------------------------------------------------------////////
  36.   public static void Main (string[] args)
  37.   {
  38.     Random R = new Random();//Random
  39.     int[] A = new int[10];//array
  40.     ////////simple intialization and output//////
  41.     ////////--------------------------------------------------////////
  42.     for (int i = 0 ; i < 10 ; i++)
  43.       A[i] = R.Next(0,10);
  44.     for (int i = 0; i < 10; i++)
  45.       Console.Write("{0} ", A[i]);
  46.     Console.WriteLine();
  47.     ////////creating a heap and output////////
  48.     ////////--------------------------------------------------////////
  49.     for (int i = (A.Length) / 2; i >= 0; i--)
  50.       repair(ref A, i, A.Length);
  51.     for (int i = 0; i < 10; i++)
  52.       Console.Write("{0} ", A[i]);
  53.     Console.WriteLine();
  54.     ////////Heap sort and output////////
  55.     ////////--------------------------------------------------////////
  56.     for (int i = A.Length - 1; i > 0; i--)
  57.     {
  58.         Swap(ref A[0], ref A[i]);
  59.         repair(ref A, 0, i);
  60.     }
  61.     for (int i = 0; i < 10; i++)
  62.       Console.Write("{0} ", A[i]);
  63.     Console.WriteLine();
  64.   }
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement