-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathHeap Sort.c
More file actions
107 lines (92 loc) · 1.49 KB
/
Heap Sort.c
File metadata and controls
107 lines (92 loc) · 1.49 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
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
95
96
97
98
99
100
101
102
103
104
105
106
107
/*
* @author: Ashish A Gaikwad <ash.gkwd@gmail.com>
* Heap sort implementation in C with menu driven program
* Ref: http://www.youtube.com/watch?v=W81Qzuz4qH0
*/
#include "stdio.h"
#define MAX 30
void shift_up(int arr[], int size)
{
int index = size - 1;
while( index > 0 )
{
int parent = (index-1)/2;
if( arr[index] > arr[parent] )
{
int tmp = arr[index];
arr[index] = arr[parent];
arr[parent] = tmp;
index = parent;
}
else
{
break;
}
}
}
void shift_down(int arr[], int size)
{
int index = 0;
int left = 2*index + 1;
while( left < size )
{
int max = left;
int right = left + 1;
if( right < size )
{
if( arr[right] > arr[left] )
{
max++;
}
}
if( arr[index] < arr[max] )
{
int temp = arr[index];
arr[index] = arr[max];
arr[max] = temp;
index = max;
left = 2*index + 1;
}
else
{
break;
}
}
}
void heap_sort(int arr[], int size)
{
int sorted[MAX];
int size_backup = size;
while( size > 0 )
{
sorted[size-1] = arr[0];
arr[0] = arr[size-1];
size--;
shift_down(arr, size);
}
for (int i = 0; i < size_backup; ++i)
{
arr[i] = sorted[i];
}
}
int main()
{
int arr[MAX];
int size;
printf("Enter Number Of Elements : ");
scanf("%d", &size);
printf("Enter values of elements : ");
for (int i = 0; i < size; ++i)
{
scanf("%d", &arr[i]);
shift_up(arr, i+1);
}
heap_sort(arr, size);
printf("Sorted elements :\n");
for (int i = 0; i < size; ++i)
{
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}