-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprirityQueqe.c
108 lines (96 loc) Β· 2.04 KB
/
prirityQueqe.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
#include <stdio.h>
int size = 0;
void swap(int *a, int *b)
{
int temp = *b;
*b = *a;
*a = temp;
}
// Function to heapify the tree
void heapify(int array[], int size, int i)
{
if (size == 1)
{
printf("Single element in the heap");
}
else
{
// Find the largest among root, left child and right child
int largest = i;
int l = 2 * i + 1;
int r = 2 * i + 2;
if (l < size && array[l] > array[largest])
largest = l;
if (r < size && array[r] > array[largest])
largest = r;
// Swap and continue heapifying if root is not largest
if (largest != i)
{
swap(&array[i], &array[largest]);
heapify(array, size, largest);
}
}
}
// Function to insert an element into the tree
void insert(int array[], int newNum)
{
int i;
if (size == 0)
{
array[0] = newNum;
size += 1;
}
else
{
array[size] = newNum;
size += 1;
for (i = size / 2 - 1; i >= 0; i--)
{
heapify(array, size, i);
}
}
}
// Function to delete an element from the tree
void deleteRoot(int array[], int num)
{
int i;
for (i = 0; i < size; i++)
{
if (num == array[i])
break;
}
swap(&array[i], &array[size - 1]);
size -= 1;
for (i = size / 2 - 1; i >= 0; i--)
{
heapify(array, size, i);
}
}
// Print the array
void printArray(int array[], int size)
{
int i;
for (i = 0; i < size; ++i)
printf("%d ", array[i]);
printf("\n");
}
// Driver code
int main()
{
int array[10];
int n, i, ele;
printf("Enter the size of array: ");
scanf("%d", &n);
printf("Enter the elements:\n");
for (i = 0; i < n; i++)
{
printf("A[%d]: ", i);
scanf("%d", &ele);
insert(array, ele);
}
printf("Max-Heap array: ");
printArray(array, size);
deleteRoot(array, array[size]);
printf("After deleting an element: ");
printArray(array, size);
}