Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 36348e4

Browse files
authored
Merge pull request fnplus#563 from VarthanV/patch-1
Created heap code
2 parents c25ff32 + 8438e0b commit 36348e4

File tree

1 file changed

+66
-0
lines changed

1 file changed

+66
-0
lines changed

‎Data Structures/Heap/C/heap.c‎

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
#include<stdio.h>
2+
#include<limits.h>
3+
4+
/*Declaring heap globally so that we do not need to pass it as an argument every time*/
5+
/* Heap implemented here is Min Heap */
6+
7+
int heap[1000000], heapSize;
8+
/*Initialize Heap*/
9+
void Init() {
10+
heapSize = 0;
11+
heap[0] = -INT_MAX;
12+
}
13+
14+
/*Insert an element into the heap */
15+
void Insert(int element) {
16+
heapSize++;
17+
heap[heapSize] = element; /*Insert in the last place*/
18+
/*Adjust its position*/
19+
int now = heapSize;
20+
while (heap[now / 2] > element) {
21+
heap[now] = heap[now / 2];
22+
now /= 2;
23+
}
24+
heap[now] = element;
25+
}
26+
27+
int DeleteMin() {
28+
29+
lastElement = heap[heapSize--];
30+
31+
for (now = 1; now * 2 <= heapSize; now = child) {
32+
33+
child = now * 2;
34+
35+
if (child != heapSize && heap[child + 1] < heap[child]) {
36+
child++;
37+
}
38+
39+
if (lastElement > heap[child]) {
40+
heap[now] = heap[child];
41+
} else /* It fits there */
42+
{
43+
break;
44+
}
45+
}
46+
heap[now] = lastElement;
47+
return minElement;
48+
}
49+
50+
int main() {
51+
int number_of_elements;
52+
printf("Program to demonstrate Heap:\nEnter the number of elements: ");
53+
scanf("%d", &number_of_elements);
54+
int iter, element;
55+
Init();
56+
printf("Enter the elements: ");
57+
for (iter = 0; iter < number_of_elements; iter++) {
58+
scanf("%d", &element);
59+
Insert(element);
60+
}
61+
for (iter = 0; iter < number_of_elements; iter++) {
62+
printf("%d ", DeleteMin());
63+
}
64+
printf("\n");
65+
return 0;
66+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /