Loading
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Rajanikant HawaldarRank #110 · 20.2K reputationPosted Nov 12, 2022, 10:10 AM EST
it divides its input into a sorted and an unsorted region, and it iteratively shrinks the unsorted region by extracting the largest element and moving that to the sorted region. It first removes the topmost item (the largest) and replace it with the rightmost leaf. The topmost item is stored in an array and Re-establish the heap.this is done until there are no more items left in the heap.
/* * C# Program to Heap Sort */ using System; class heapsort { int[] r = { 2,5,1,10,6,9,3,7,4,8}; public void hsort() { int i, t; for (i = 5; i >= 0; i--) { adjust(i, 9); } for (i = 8; i >= 0; i--) { t = r[i + 1]; r[i + 1] = r[0]; r[0] = t; adjust(0, i); } } private void adjust(int i, int n) { int t, j; try { t = r[i]; j = 2 * i; while (j =r[j]) break; r[j / 2] = r[j]; j *= 2; } r[j / 2] = t; } catch (IndexOutOfRangeException e) { Console.WriteLine("Array Out of Bounds ", e); } } public void print() { for (int i = 0; i < 10; i++) { Console.WriteLine("{0}", r[i]); } } public static void Main() { heap obj = new heap(); Console.WriteLine("Elements Before sorting : "); obj.print(); obj.hsort(); Console.WriteLine("Elements After sorting : "); obj.print(); Console.Read(); } }Elements Before Sorting :
2
5
1
10
6
9
3
7
4
8
Elements After Sorting :
1
2
3
4
5
6
7
8
9
10
Brahma Prakash ShuklaRank #633 · 3.8K reputationPosted Nov 12, 2022, 6:59 AM EST
https://www.google.com/amp/s/www.geeksforgeeks.org/heap-sort/amp/