-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathheapsort.c
94 lines (70 loc) · 2.07 KB
/
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
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
83
84
85
86
87
88
89
90
91
92
93
94
#include <stdio.h>
#define MAX 1000
int num;
int arr[MAX];
void MaxHeapify(int list[], int index, int heapsize)
{
int parent = list[index];
int leftchild = list[index*2];
int rightchild = list[index*2 +1];
int largest = index; //that means, parent index is set to largest first
/* Find larger between parent and leftchild */
if (index*2 <= heapsize && leftchild > list[largest])
largest = index*2;
/* Find larger between larger from last operation and right child */
if ((index*2+1) <= heapsize && rightchild > list[largest])
largest = index*2 + 1;
/* Parent is not largest any more that means, left or rightchild is larger */
if (largest != index) {
/* Swap parent and whichever is largest */
int temp = parent;
if (largest == index*2) {
list[index] = list[index*2];
list[index*2] = temp;
MaxHeapify(list, index*2, heapsize);
} else {
list[index] = list[index*2+1];
list[index*2+1] = temp;
MaxHeapify(list, index*2+1, heapsize);
}
}
}
void BuildMaxHeap(int list[], int heapsize)
{
int k;
for (k= (heapsize/2); k >=1; k--) {
MaxHeapify(list, k, heapsize);
}
}
void HeapSort(int list[], int num)
{
int k;
int heapsize = num;
/* Create Max-Heap */
BuildMaxHeap(list, heapsize);
printf("After build heap, lets check...\n");
for(k=1; k <= num; k++)
printf("[%d]", arr[k]);
printf("\n");
/* Until heapsize is 1, Swap root node of Max heap with last child and call Max-Heap*/
while(heapsize >1){
/*Swap */
int temp = list[1];
list[1] = list[heapsize];
list[heapsize] = temp;
heapsize--;
MaxHeapify(list, 1, heapsize);
}
}
int main()
{
int k;
printf("Welcome to HeapSort Implementation...\n");
printf("Enter number of nodes...\n");
scanf("%d", &num);
for(k=1; k <= num; k++)
scanf("%d", &arr[k]);
HeapSort(arr, num);
for(k=1; k <= num; k++)
printf("[%d]", arr[k]);
}