-
Notifications
You must be signed in to change notification settings - Fork 2
/
heapSort.c
54 lines (50 loc) · 894 Bytes
/
heapSort.c
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
/*
Program for performing heap sort algorithm
Author: Vivek K J
S3 CSA
*/
#include<stdio.h>
int arr[20], n;
void heapify(int a,int i){
int largest, left, right, temp;
largest = i;
left = 2*i+1;
right = 2*i+2;
if(left<a && arr[left] > arr[largest]){
largest = left;
}
if(right<a && arr[right] > arr[largest]){
largest = right;
}
if(largest != i){
temp = arr[i];
arr[i] = arr[largest];
arr[largest] = temp;
heapify(a, largest);
}
}
void HeapSort(){
int i, temp;
for(i=n/2-1; i>=0; i--){
heapify(n,i);
}
for(i=n-1; i>=0; i--){
temp = arr[0];
arr[0] = arr[i];
arr[i] = temp;
heapify(i,0);
}
}
void main(){
printf("Enter Size of Array: ");
scanf("%d", &n);
printf("Enter Array Elements: \n");
for(int i=0; i<n; i++){
scanf("%d", &arr[i]);
}
HeapSort();
printf("Array after sorting is: \n");
for(int i=0; i<n; i++){
printf("%d \t", arr[i]);
}
}