-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathheap_sort.cpp
82 lines (71 loc) · 1.62 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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
/*
heap works on array but represented as complete binary Tree
start from index 1....n
get left child of any element =i*2 where is index of element of the element
get right child of any element =(i*2)+1 where is index of element of the element
get parent of any element=floor(i/2) where is index of element of the element
start from index 0....n-1
get left child of any element =i*2+1 where is index of element of the element
get right child of any element =(i*2)+2 where is index of element of the element
get parent of any element=floor(i/2)-1 where is index of element of the element
*/
#include<iostream>
using namespace std;
void max_heapify(int arr[],int n,int i)// max heapify
{
int l=2*i+1;
int r=2*i+2;
int max=i;
if(l<n&&arr[l]>arr[max])
max=l;
if(r<n&&arr[r]>arr[max])
max=r;
if(max != i){
swap(arr[i],arr[max]);
max_heapify(arr,n,max);
}
}
void min_heapify(int arr[],int n,int i)// min heapify
{
int l=2*i+1;
int r=2*i+2;
int max=i;
if(l<n&&arr[l]<arr[max])
max=l;
if(r<n&&arr[r]<arr[max])
max=r;
if(max != i){
swap(arr[i],arr[max]);
min_heapify(arr,n,max);
}
}
void buildHeap(int arr[],int n)
{
for (int i = n / 2 - 1; i >= 0; i--)
max_heapify(arr, n, i);
}
void heapSort(int arr[], int n)
{
buildHeap(arr, n);
for (int i = n-1; i >=0; i--)
{
swap(arr[0], arr[i]);
max_heapify(arr, i, 0);
}
}
void print(int arr[], int n)
{
for (int i = 0; i < n; i++)
{
cout << arr[i] << " ";
}
cout << endl;
}
int main()
{
int arr[] = { 90,10,40,70,5 };
int n = sizeof(arr) / sizeof(arr[0]);
heapSort(arr, n);
print(arr, n);
return 0;
}