-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathBinary_Heaps_merge.c
68 lines (51 loc) · 1.38 KB
/
Binary_Heaps_merge.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
// Implementation of merging of two heaps with dynamic insertion and deletion.
#include <stdio.h>
#include <stdlib.h>
void swap(int* a, int* b) {
int temp = *a;
*a = *b;
*b = temp;
}
void minHeapify(int A[], int size, int i) {
int smallest = i;
int L = 2 * i + 1;
int R = 2 * i + 2;
if (L < size && A[L] < A[smallest])
smallest = L;
if (R < size && A[R] < A[smallest])
smallest = R;
if (smallest != i) {
swap(&A[i], &A[smallest]);
minHeapify(A, size, smallest);
}
}
void buildMinHeap(int A[], int size) {
for (int i = size / 2 - 1; i >= 0; i--) {
minHeapify(A, size, i);
}
}
void mergeHeaps(int A1[], int A2[], int size1, int size2) {
int mergedSize = size1 + size2;
int* mergedHeap = (int*)malloc(mergedSize * sizeof(int));
for (int i = 0; i < size1; i++) {
mergedHeap[i] = A1[i];
}
for (int i = 0; i < size2; i++) {
mergedHeap[size1 + i] = A2[i];
}
buildMinHeap(mergedHeap, mergedSize);
printf("Merged Heap: ");
for (int i = 0; i < mergedSize; i++) {
printf("%d ", mergedHeap[i]);
}
printf("\n");
free(mergedHeap);
}
int main() {
int A1[] = {6, 7, 8};
int A2[] = {23, 24, 30, 59};
int size1 = sizeof(A1) / sizeof(A1[0]);
int size2 = sizeof(A2) / sizeof(A2[0]);
mergeHeaps(A1, A2, size1, size2);
return 0;
}