TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
heap_sort.cpp
Go to the documentation of this file.
1
23#include <algorithm>
24#include <cassert>
25#include <iostream>
26
36template <typename T>
37void printArray(T *arr, int sz) {
38 for (int i = 0; i < sz; i++) std::cout << arr[i] << " ";
39 std::cout << "\n";
40}
41
57template <typename T>
58void heapify(T *arr, int n, int i) {
59 int largest = i;
60 int l = 2 * i + 1;
61 int r = 2 * i + 2;
62
63 if (l < n && arr[l] > arr[largest])
64 largest = l;
65
66 if (r < n && arr[r] > arr[largest])
67 largest = r;
68
69 if (largest != i) {
70 std::swap(arr[i], arr[largest]);
71 heapify(arr, n, largest);
72 }
73}
74
83template <typename T>
84void heapSort(T *arr, int n) {
85 for (int i = n - 1; i >= 0; i--) heapify(arr, n, i);
86
87 for (int i = n - 1; i >= 0; i--) {
88 std::swap(arr[0], arr[i]);
89 heapify(arr, i, 0);
90 }
91}
92
99void test() {
100 std::cout << "Test 1\n";
101 int arr[] = {-10, 78, -1, -6, 7, 4, 94, 5, 99, 0};
102 int sz = sizeof(arr) / sizeof(arr[0]); // sz - size of array
103 printArray(arr, sz); // displaying the array before sorting
104 heapSort(arr, sz); // calling heapsort to sort the array
105 printArray(arr, sz); // display array after sorting
106 assert(std::is_sorted(arr, arr + sz));
107 std::cout << "Test 1 Passed\n========================\n";
108
109 std::cout << "Test 2\n";
110 double arr2[] = {4.5, -3.6, 7.6, 0, 12.9};
111 sz = sizeof(arr2) / sizeof(arr2[0]);
112 printArray(arr2, sz);
113 heapSort(arr2, sz);
114 printArray(arr2, sz);
115 assert(std::is_sorted(arr2, arr2 + sz));
116 std::cout << "Test 2 passed\n";
117}
118
120int main() {
121 test();
122 return 0;
123}
double l(double x)
Another test function.
void heapSort(T *arr, int n)
Definition heap_sort.cpp:84
void printArray(T *arr, int sz)
Definition heap_sort.cpp:37
void test()
Definition heap_sort.cpp:99
int main()