-
Notifications
You must be signed in to change notification settings - Fork 1k
/
Copy pathHeapSort.cs
110 lines (93 loc) · 2.64 KB
/
HeapSort.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
/*
C# Program to Perform a Heap Sort
Heap Sort is a popular and efficient sorting algorithm.Heap sort is a comparison
based sorting technique based on Binary Heap data structure. It is similar to
selection sort where we first find the minimum element and place the minimum
element at the beginning. We repeat the same process for the remaining elements.
*/
using System;
public class HeapSort
{
static void Sort(int[] array, int length)
{
//Build max heap
for (int i = length / 2 - 1; i >= 0; i--)
{
Heapify(array, length, i);
}
for (int i = length - 1; i >= 0; i--)
{
//Swap
int temp = array[0];
array[0] = array[i];
array[i] = temp;
//Heapify root element
Heapify(array, i, 0);
}
}
//Rebuilds the heap
static void Heapify(int[] array, int length, int i)
{
//Find largest among root and children
int max = i;
int left = 2 * i + 1;
int right = 2 * i + 2;
if (left < length && array[left] > array[max])
{
max = left;
}
if (right < length && array[right] > array[max])
{
max = right;
}
//If root is not largest, swap with largest and continue heapifying
if (max != i)
{
int swap = array[i];
array[i] = array[max];
array[max] = swap;
Heapify(array, length, max);
}
}
public static void Main()
{
//Take array size input
Console.Write("Enter array size: ");
int length = Convert.ToInt32(Console.ReadLine());
int[] array = new int[length];
//Take array elements input
for(int i=0; i<length; i++){
Console.Write("Element {0} : ", i);
array[i] = Convert.ToInt32(Console.ReadLine());
}
//Print array before Heap sort
Console.Write("\nThe Array Before Heap Sort is: ");
for(int i=0; i<length; i++)
{
Console.Write(array[i]+ " ");
}
Sort(array,length);
//Print array after Heap sort
Console.Write("\nThe Array After Heap Sort is: ");
for (int i=0; i<length; i++)
{
Console.Write(array[i]+ " ");
}
}
}
/*
Input:
Enter array size: 5
Element 0 : 34
Element 1 : 73
Element 2 : 17
Element 3 : 61
Element 4 : 45
Output:
The Array Before Heap Sort is: 34 73 17 61 45
The Array After Heap Sort is: 17 34 45 61 73
*/
/*
Time complexity: O(nLogn)
Space complexity: O(1)
*/