-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHeapSort.cpp
More file actions
64 lines (49 loc) · 1.18 KB
/
HeapSort.cpp
File metadata and controls
64 lines (49 loc) · 1.18 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
#include <iostream>
// Heap Sort (Not Adaptive & Stable)
// Time Average & Best & Worst: O(n logn) || Space: O(1)
void heapify(int A[], int arrSize, int i);
void HeapSort(int A[], int arrSize)
{
for (int i = arrSize / 2 - 1; i >= 0; --i)
heapify(A, arrSize, i);
for (int i = arrSize - 1; i > 0; --i)
{
std::swap(A[0], A[i]);
heapify(A, i, 0);
}
}
void heapify(int A[], int arrSize, int i)
{
int l = 2 * i + 1;
int r = 2 * i + 2;
int largest = i;
if (l < arrSize && A[largest] < A[l])
largest = l;
if (r < arrSize && A[largest] < A[r])
largest = r;
if (largest != i)
{
std::swap(A[i], A[largest]);
heapify(A, arrSize, largest);
}
}
void printArr(int arr[], int arrSize)
{
std::cout << "{ ";
for (int i = 0; i < arrSize; ++i)
{
std::cout << arr[i] << " ";
}
std::cout << "}" << std::endl;
}
int main()
{
int A[] = {5, 2, 7, 45, 3, 79, 4, 23, 45, 23, 17, 4, 56, 120};
int aSize = sizeof(A) / sizeof(A[0]);
std::cout << "A: ";
printArr(A, aSize);
HeapSort(A, aSize);
std::cout << "A after Heap Sort: ";
printArr(A, aSize);
return 0;
}