Demonstrating Heap Sort in C#
Submitted by janobe on Monday, December 10, 2018 - 22:10.
Now, let’s learn how to demonstrate heap sort program in C#. But, before anything else let’s know what heapsort is? Here’s a short definition of it, heapsort is a comparison-based sorting algorithm that uses the heap data structure. In this program, the topmost item (the largest) is removed first and stored in an array. Then, it is replaced by the rightmost leaf and re-established the heap. The same process is repeated until there are no more items left in the heap and the array is sorted. Let’s begin:
For any questions about this article. You can contact me @
Email – [email protected]
Mobile No. – 09305235027 – TNT
Or feel free to comment below.
Creating Application
Step 1
Open Microsoft Visual Studio 2015 and create a new windows form application in c#.Step 2
Do the form just like shown below.Step 3
Create a method for the heap sort.- int[] numbers = { 2, 5, 1, 10, 6, 9, 3, 7, 4, 8 };
- public void heapsort()
- {
- int i, c;
- for (i = 5; i >= 0; i--)
- {
- adjust(i, 9);
- }
- for (i = 8; i >= 0; i--)
- {
- c= numbers[i + 1];
- numbers[i + 1] = numbers[0];
- numbers[0] = c;
- adjust(0, i);
- }
- }
- private void adjust(int i, int n)
- {
- int a, b;
- try
- {
- a = numbers[i];
- b = 2 * i;
- while (b <= n)
- {
- if (b < n && numbers[b] < numbers[b + 1])
- b++;
- if (a >= numbers[b])
- break;
- numbers[b / 2] = numbers[b];
- b *= 2;
- }
- numbers[b / 2] = a;
- }
- catch (IndexOutOfRangeException e)
- {
- listBox1.Items.Add("Array Out of Bounds " + e);
- }
- }
- public void display()
- {
- for (int i = 0; i < 10; i++)
- {
- listBox1.Items.Add("{"+ i++ + "}" + numbers[i]);
- }
- }
Step 4
Double click the button and call the method that you have created for the heap sort in the click event handler of the button to execute when the button is click.- listBox1.Items.Clear();
- listBox1.Items.Add("Array Elements Before sorting : ");
- display();
- heapsort();
- listBox1.Items.Add("Array Elements After sorting : ");
- display();
Add new comment
- 334 views