-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHeap_sort using Heapify algorithm
More file actions
54 lines (50 loc) · 1.22 KB
/
Heap_sort using Heapify algorithm
File metadata and controls
54 lines (50 loc) · 1.22 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
Class Sorting algorithm
Data structure Array
Worst-case performance {\displaystyle O(n\log n)}O(n\log n)
Best-case performance {\displaystyle O(n\log n)}O(n\log n) (distinct keys)
or {\displaystyle O(n)}O(n) (equal keys)
Average performance {\displaystyle O(n\log n)}O(n\log n)
Worst-case space complexity
Code->
#include<bits/stdc++.h>
using namespace std;
// Building Heapify algorihtm
// Time Complexity is O(n)
void Heapify(int arr[],int n,int i){
int largest=i;
int left=2*i;
int right=2*i+1;
if(left<=n && arr[largest]<arr[left]){
largest=left;
}
if(right<=n && arr[largest]<arr[right]){
largest=right;
}
// checking the parent Node of its right position
if(largest!=i){
swap(arr[largest],arr[i]);
Heapify(arr,n,largest);
}
}
void Heapsort(int arr[],int n){
int size=n;
while(size>1){
swap(arr[size],arr[1]);
size--;
Heapify(arr,size,1);
}
}
int main(){
int n=5;
int arr[6]={-1,54,53,55,52,50};
// max-> heap creation
for(int i=n/2;i>0;i--){
Heapify(arr,n,i);
}
// Heapsort
Heapsort(arr,n);
//printing the array in asscending order
for(int i=1;i<=n;i++){
cout<<arr[i]<<" ";
}
}