-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathheapsort.cpp
84 lines (66 loc) · 1.31 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
// Program to implement Heap Sorting
#include <iostream>
#define LEFT(X) 2*X
#define RIGHT(X) ( 2*X + 1 )
using namespace std;
int size;
int count = 0;
void maxHeapify( int a[], int i )
{
int largest;
int l = LEFT(i);
int r = RIGHT(i);
if( l <= size && a[l] > a[i] )
largest = l;
else
largest = i;
if( r <= size && a[r] > a[largest] )
largest = r;
count++;
if( largest != i )
{
int temp = a[i];
a[i] = a[largest];
a[largest] = temp;
maxHeapify( a, largest );
}
}
void build_max_heap( int a[] )
{
for( int i = (size / 2); i > 0; i-- )
maxHeapify( a, i );
}
void heapsort( int a[] )
{
int i;
int temp;
int heap_size = size;
build_max_heap(a);
for( i = size; i >= 2; i-- )
{
temp = a[1];
a[1] = a[i];
a[i] = temp;
heap_size--;
maxHeapify( a, 1 );
}
}
int main()
{
cout << " \n\t\t\t Heap Sorting \n\t\t\t ";
cout << " \n\t\t\t Enter the size of array: \n\t\t\t ";
cin >> size;
int *a = new int [size + 1];
cout << " \n\t\t\t Enter the elements of an unsorted array \n\t\t\t ";
for( int i = 1; i <= size; i++ )
{ cout << " \n\t\t\t "; cin >> a[i]; }
heapsort(a);
cout << " \n\t\t\t Sorted array \n\t\t\t ";
for( int j = 1; j <= size; j++ )
{
cout << a[j] << " ";
}
cout << " \n\n\t\t\t The no. of comparisons are: " << count;
cout << "\n\n";
return 0;
}