forked from HarshCasper/NeoAlgo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MAX_MIN_HeapSort.c
122 lines (113 loc) · 3.6 KB
/
MAX_MIN_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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
/* C code for Heap Sorting*/
#include<stdio.h>
void maxHeap(int[], int);
void minHeap(int[], int);
int temp;
//function for maxHeap Sort
void maxHeap(int arr[], int len) {
int pos, maxH;
for (int i = 1; i < len; i++) {
pos = i;
do {
maxH = (pos - 1) / 2;
/* to build MAXHEAP array */
if (arr[maxH] < arr[pos]) {
temp = arr[maxH];
arr[maxH] = arr[pos];
arr[pos] = temp;
}
pos = maxH;
} while (pos != 0);
}
printf("Heap array : \n");
printf("Max Heap\n");
for (int i = 0; i < len / 2; i++) {
printf("Parent : %d Left Child : %d Right Child : %d\n", arr[i], arr[2 * i + 1], arr[2 * i + 2]);
}
for (int j = len - 1; j >= 0; j--) {
temp = arr[0];
arr[0] = arr[j];
arr[j] = temp;
maxH = 0;
do {
pos = 2 * maxH + 1;
if ((arr[pos] < arr[pos + 1]) && pos < j - 1)
pos++;
if (arr[maxH] < arr[pos] && pos < j) {
temp = arr[maxH];
arr[maxH] = arr[pos];
arr[pos] = temp;
}
maxH = pos;
} while (pos < j);
}
}
//Function for MinHeap Sort
void minHeap(int arr[], int len) {
int pos, minH;
for (int i = 1; i < len; i++) {
pos = i;
do {
minH = (pos - 1) / 2;
/* to build MINHEAP array */
if (arr[minH] > arr[pos]) {
temp = arr[minH];
arr[minH] = arr[pos];
arr[pos] = temp;
}
pos = minH;
} while (pos != 0);
}
printf("Min Heap\n");
for (int i = 0; i < len / 2; i++) {
printf("Parent : %d Left Child : %d Right Child : %d\n", arr[i], arr[2 * i + 1], arr[2 * i + 2]);
}
for (int j = len - 1; j >= 0; j--) {
temp = arr[0];
arr[0] = arr[j];
arr[j] = temp;
minH = 0;
do {
pos = 2 * minH + 1;
if ((arr[pos] > arr[pos + 1]) && pos < j - 1)
pos++;
if (arr[minH] > arr[pos] && pos < j) {
temp = arr[minH];
arr[minH] = arr[pos];
arr[pos] = temp;
}
minH = pos;
} while (pos < j);
}
}
//driver code to check above function
int main() {
int size;
printf("Input-->\n");
printf("Enter the size of array :\n");
scanf("%d", & size);
int arr[size];
printf("Enter the elements of array :\n");
for (int i = 0; i < size; i++) {
scanf("%d", & arr[i]);
}
maxHeap(arr, size);
minHeap(arr, size);
return 0;
}
/*
Input-->
Enter the size of array :
3
Enter the elements of array :
12
15
56
Heap array :
Max Heap
Parent : 56 Left Child : 12 Right Child : 15
Min Heap
Parent : 12 Left Child : 15 Right Child : 56
Time Complexity : O(n log n)
Space Complexity : O(1)
*/