Skip to content

Commit d11036b

Browse files
committed
heap sort added
1 parent 12a7de4 commit d11036b

File tree

2 files changed

+61
-1
lines changed

2 files changed

+61
-1
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -177,7 +177,8 @@ For eg storing the minimum so far in another stack so that each time when a numb
177177
### Heaps
178178

179179
- [Given an array, create a max heap](/heaps/question1.c)
180-
- [Given a max heap, apply different heap operations (find max, delete max,increase key, insert key, decrease key.)](/heaps/question1.c)
180+
- [Given a max heap, apply different heap operations (find max, delete max,increase key, insert key, decrease key.)](/heaps/question2.c)
181+
- [Write a program for heap sort](/heaps/question3.c)
181182

182183
## Some important concepts to solve algos better
183184

heaps/question3.c

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
/*
2+
Program to write heap sort
3+
4+
Time complexity: O(nlogn)
5+
because max heapify is called n times and for nearly n/2 times the height of the tree remains same (maximum),
6+
therefore here it will be nlogn only
7+
*/
8+
9+
#include <stdio.h>
10+
#include <stdlib.h>
11+
12+
void maxHeapify(int arr[],int i,int size){
13+
if(size < 1){
14+
return;
15+
}
16+
int left = 2*i+1,right=2*i+2,largest, temp, heapSize = size;
17+
if(left <= heapSize-1 && arr[left] > arr[i]){
18+
largest = left;
19+
}else{
20+
largest = i;
21+
}
22+
if(right <= heapSize-1 && arr[right] > arr[largest]){
23+
largest = right;
24+
}
25+
26+
if(largest <= heapSize-1 && largest != i){
27+
temp = arr[largest];
28+
arr[largest] = arr[i];
29+
arr[i]=temp;
30+
maxHeapify(arr,largest,size);
31+
}
32+
}
33+
34+
void display(int arr[],int size){
35+
for(int i=0;i<size;i++){
36+
printf("%d\t", arr[i]);
37+
}
38+
printf("\n");
39+
}
40+
41+
void heapSort(int arr[], int size){
42+
int temp;
43+
for(int i=size-1;i>=1;i--){
44+
temp = arr[0];
45+
arr[0] = arr[i];
46+
arr[i]=temp;
47+
maxHeapify(arr,0,i);
48+
}
49+
display(arr,size);
50+
}
51+
52+
int main(){
53+
int heap[] = {100,20,30,10,15,7,16};
54+
int size = sizeof(heap)/sizeof(heap[0]);
55+
56+
heapSort(heap,size);
57+
58+
return 0;
59+
}

0 commit comments

Comments
 (0)