-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmaxHeapSort.c
More file actions
76 lines (63 loc) · 1.07 KB
/
maxHeapSort.c
File metadata and controls
76 lines (63 loc) · 1.07 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
/*
Heap Sort Algorithm :
Avg case : o(nlogn)
Not Adaptive : Not Adaptive
Stable : Not Stable
*/
#include <stdio.h>
void show(int arr[], int n, int i)
{
int l = i * 2 + 1;
int r = i * 2 + 2;
int max = i;
if (r < n)
{
if (arr[l] < arr[r])
{
max = r;
}
else
{
max = l;
}
}
else if (l < n)
{
max = l;
}
if (arr[max] > arr[i])
{
int temp = arr[max];
arr[max] = arr[i];
arr[i] = temp;
show(arr, n, max);
}
}
void heapify(int arr[], int n)
{
for (int i = n / 2 - 1; i >= 0; i--)
{
show(arr, n, i);
}
}
void DelInHeap(int arr[], int n)
{
for (int i = n - 1; i > 0; i--)
{
int temp = arr[i];
arr[i] = arr[0];
arr[0] = temp;
heapify(arr, i); // or show(arr,i,0);
}
}
void main()
{
int arr[] = {8, 3, 4, 7, 2, 5, -4, 0, -6, 1};
int n = 10;
heapify(arr, n);
DelInHeap(arr, n);
for (int i = 0; i < n; i++)
{
printf("%d ", arr[i]);
}
}