-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathheapsort.cpp
More file actions
64 lines (53 loc) · 1.21 KB
/
Copy pathheapsort.cpp
File metadata and controls
64 lines (53 loc) · 1.21 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
// Example program
#include <iostream>
#include <string>
using namespace std;
void heapIf(int num_arr[], int size, int n)
{
int largest = n;
int leftChild = 2 * n + 1;
int rightChild = 2 * n + 2;
if(leftChild < size && num_arr[leftChild] > num_arr[largest])
{
largest = leftChild;
}
if(rightChild < size && num_arr[rightChild] > num_arr[largest])
{
largest = rightChild;
}
if(largest != n)
{
swap(num_arr[n], num_arr[largest]);
heapIf(num_arr, size, largest);
}
}
void heapSort(int num_arr[], int s)
{
for(int c = s / 2 - 1; c >= 0; c--)
{
heapIf(num_arr, s, c);
}
for(int c = s - 1; c >= 0; c--)
{
swap(num_arr[0], num_arr[c]);
heapIf(num_arr, c, 0);
}
}
//This function prints the array
void printArray(int num_arr[], int n)
{
for(int c = 0; c < n; c++)
{
cout << num_arr[c] << " ";
}
cout << "\n";
}
int main()
{
cout << "Heap Sort" << "\n";
int num_arr[] = {12, 33, 10, 45, 3, 15};
int size = sizeof(num_arr)/ sizeof(num_arr[0]);
heapSort(num_arr, size);
cout << "Sorting completed \n";
printArray(num_arr, size);
}