-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathheapsort.cpp
More file actions
57 lines (54 loc) · 1004 Bytes
/
heapsort.cpp
File metadata and controls
57 lines (54 loc) · 1004 Bytes
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
#include<stdio.h>
int n;
void max_heapify(int *arr,int parent){
int largest,l,r,temp;
l = 2*parent+1;
r = 2*parent+2;
if(l<n && arr[l]>arr[parent]){
largest = l;
}
else{
largest = parent;
}
if(r<n && arr[r]>arr[largest]){
largest = r;
}
if(largest!=parent){
temp = arr[parent];
arr[parent] = arr[largest];
arr[largest] = temp;
max_heapify(arr,largest);
}
}
void build_heap(int *arr){
int i;
for(i=(n/2)-1;i>=0;i--){
max_heapify(arr,i);
}
}
void heap_sort(int *arr){
int max,i;
for(i=n-1;i>=0;i--){
max = arr[0];
arr[0] = arr[n-1];
n--;
max_heapify(arr,0);
printf("%d ",max);
}
}
int main(){
printf("Enter no of elements:");
scanf("%d",&n);
int arr[n],i;
printf("\nEnter the array elements:");
for(i=0;i<n;i++){
scanf("%d",&arr[i]);
}
build_heap(arr);
printf("\nHeap after building:");
for(i=0;i<n;i++){
printf("%d ",arr[i]);
}
printf("\nSorted elements are:");
heap_sort(arr);
}