-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
78 lines (64 loc) · 2.65 KB
/
Program.cs
File metadata and controls
78 lines (64 loc) · 2.65 KB
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
using System;
namespace HeapSortNess
{
public class Program
{
static void Main(string[] args)
{
int[] arr = { 6, 2, 5, 1, -2, 43, 22, 2 };
HeapSort(arr);
foreach (int item in arr)
{
Console.WriteLine(item);
}
}
// Function to recieve array of integeres and sort it according to the Heap Sort algorithm
public static void HeapSort(int[] arr)
{
int heapSize = arr.Length;
BuildMaxHeap(arr);
// One by one replace the largest element on the heap with the last element from the unsorted partition
for (int i = heapSize - 1; i >= 1; i--)
{
Swap(arr, i, 0);
heapSize--;
Heapify(arr, heapSize, 0);
}
}
// Function to receive an unsorted array of integers and creates a Max Heap from it
public static void BuildMaxHeap(int[] arr)
{
int heapSize = arr.Length;
for (int i = heapSize / 2 - 1; i >= 0; i--)
Heapify(arr, heapSize, i);
}
// Function to return the array back to its Max Heap form, will traverse each time from the startIndex downwards
public static void Heapify(int[] arr, int heapSize, int startIndex)
{
int largest = startIndex;
int leftChild = 2 * startIndex + 1; // Find the left child
int rightChild = 2 * startIndex + 2; // Find the right child
// If the left child is larger than the root, replace its index with the largest element
if (leftChild < heapSize && arr[leftChild] > arr[largest])
largest = leftChild;
// If the right child is larger than the root, replace its index with the largest element
if (rightChild < heapSize && arr[rightChild] > arr[largest])
largest = rightChild;
// If largest is not the root
if (largest != startIndex)
{
// Swap between the largest element in the array and the last element in the unsorted partition
Swap(arr, startIndex, largest);
// Recursively reorder the heap until it becomes max heap again
Heapify(arr, heapSize, largest);
}
}
// Function to swap between 2 integers in a given integers array
public static void Swap(int[] arr, int firstPosition, int secondPosition)
{
int temp = arr[firstPosition];
arr[firstPosition] = arr[secondPosition];
arr[secondPosition] = temp;
}
}
}