-
Notifications
You must be signed in to change notification settings - Fork 0
/
heapsort.cpp
86 lines (58 loc) · 1.23 KB
/
heapsort.cpp
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
//author--> Gourob Mazumder
#include<iostream>
#define MAX 100
using namespace std;
void heapsort(int * , int );
void maxheap(int *, int, int );
void display(int *, int );
int main()
{
int num[MAX], size;
cout << "How many elements do you want to sort? " << endl;
cin >> size;
for (int i = 0; i < size; ++i)
{
cin >> num[i];
}
cout << endl << endl << "unsorted array" << endl;
display(num, size);
heapsort(num, size);
cout << endl << endl << "sorted array" << endl;
display(num, size);
return 0;
}
void heapsort(int *num, int size)
{
for (int i = (size / 2) - 1; i >= 0 ; --i)
{
maxheap(num, size, i);
}
for (int i = size - 1; i >= 0; --i)
{
swap(num[0], num[i]);
maxheap(num, i, 0);
}
}
void maxheap(int *num, int size, int root)
{
int max = root;
int left = (2 * root) + 1;
int right = (2 * root) + 2;
if (left < size && num[max] < num[left])
max = left;
if (right < size && num[root] < num[right])
max = right;
if (max != root)
{
swap(num[root], num[max]);
maxheap(num, size, max);
}
}
void display(int *num, int size)
{
for (int i = 0; i < size; ++i)
{
cout << num[i] << " ";
}
cout << endl;
}