-
Notifications
You must be signed in to change notification settings - Fork 155
/
Heap_sort.cpp
64 lines (52 loc) · 1.12 KB
/
Heap_sort.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
//Implementation of Heap Sort
#include <iostream>
using namespace std;
//Program by Siddharth Bhamare
void convertHeap(int arr[], int len, int x)
{
int largest = x;
int left = 2 * x + 1;
int right = 2 * x + 2;
if (left < len && arr[left] > arr[largest])
largest = left;
if (right < len && arr[right] > arr[largest])
largest = right;
if (largest != x)
{
swap(arr[x], arr[largest]);
convertHeap(arr, len, largest);
}
}
void HeapSort(int arr[], int len)
{
for (int i = len / 2 - 1; i >= 0; i--)
convertHeap(arr, len, i);
for (int i = len - 1; i >= 0; i--)
{
swap(arr[0], arr[i]);
convertHeap(arr, i, 0);
}
}
void show(int arr[], int len)
{
cout << "\nSorted Array is : ";
for (int i = 0; i < len; ++i)
cout << arr[i] << " ";
cout << endl;
}
int main()
{
int i=0,n;
cout <<"Enter size of Array : ";
cin >>n;
int arr[n];
cout <<"Enter elements of Array : ";
while(i<n)
{
cin>>arr[i];
i++;
}
int m = sizeof(arr) / sizeof(int);
HeapSort(arr, m);
show(arr, m);
}