Skip to content

Commit 7058b32

Browse files
committed
Binary Heap added
1 parent ca2a53e commit 7058b32

File tree

6 files changed

+198
-0
lines changed

6 files changed

+198
-0
lines changed

Data Structure/Binary Heap/README.md

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
# Binary Heap
2+
3+
A **binary heap** is a complete binary tree which satisfies the heap ordering property. The ordering can be one of two types:
4+
5+
- *min-heap property:* the value of each node is greater than or equal to the value of its parent, with the minimum-value element at the root.
6+
- *max-heap property:* the value of each node is less than or equal to the value of its parent, with the maximum-value element at the root.
7+
8+
A heap is a "complete tree" -- a complete tree is one in which there are no gaps between leaves. For instance, a tree with a root node that has only one child must have its child as the left node. More precisely, a complete tree is one that has every level filled in before adding a node to the next level, and one that has the nodes in a given level filled in from left to right, with no breaks.
9+
10+
![Binary Heap](heap.bmp)
11+
12+
In a heap the highest (or lowest) priority element is always stored at the root, hence the name "heap". A heap is not a sorted structure and can be regarded as partially ordered. As you see from the picture, there is no particular relationship among nodes on any given level, even among the siblings.
13+
14+
Since a heap is a complete binary tree, it has a smallest possible height - a heap with N nodes always has O(log N) height.
15+
16+
A heap is useful data structure when you need to remove the object with the highest (or lowest) priority. A common use of a heap is to implement a priority queue.
17+
18+
Here we will continue discussion with **Max Heap**.
19+
20+
**Min Heap** is same as **Max Heap** with just a simple comparison variation.
21+
22+
---
23+
**Array Implementation**
24+
25+
A complete binary tree can be uniquely represented by storing its level order traversal in an array.
26+
27+
![Heap implementation in array](complete.bmp)
28+
29+
When we add elements to a heap, we fill it's tree-like structure from left to right, level by level. This makes heaps really easy to implement in an array, where the value for some index 's left child is located at index and the value for its right child is at index (using zero-indexing).
30+
31+
---
32+
**Max Heap Construction:**
33+
34+
The new element is initially appended to the end of the heap (as the last element of the array). The heap property is repaired by comparing the added element with its parent and moving the added element up a level (swapping positions with the parent). This process is called "percolation up". The comparison is repeated until the parent is larger than or equal to the percolating element.
35+
36+
![Max Heap Insertion](max_heap_insertion.gif)
37+
38+
The worst-case runtime of the algorithm is O(log n), since we need at most one swap on each level of a heap on the path from the inserted node to the root.
39+
40+
**Max Heap Deletion:**
41+
42+
The maximum element can be found at the root, which is the first element of the array. We remove the root and replace it with the last element of the heap and then restore the heap property by percolating down.
43+
44+
![Max Heap Deletion](max_heap_deletion_animation.gif)
45+
46+
Similar to insertion, the worst-case runtime is O(log n).
47+
48+
#### Complexity Analysis
49+
- Insert - O(log n)
50+
- Delete Max - O(log n)
51+
- Find Max - O(1)
52+
- Remove - O(log n)
53+
54+
### More on this topic
55+
- https://en.wikipedia.org/wiki/Heap_(data_structure)
56+
- https://www.cs.auckland.ac.nz/software/AlgAnim/heaps.html
57+
- https://www.cs.cmu.edu/~adamchik/15-121/lectures/Binary%20Heaps/heaps.html
58+
- http://www.cprogramming.com/tutorial/computersciencetheory/heap.html https://www.tutorialspoint.com/data_structures_algorithms/heap_data_structure.htm
Lines changed: 140 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,140 @@
1+
//This is an implementation of Max Heap using Array
2+
3+
#include<stdio.h>
4+
5+
#define SZ 100
6+
7+
int getParentPos(int pos, int lastPos)
8+
{
9+
if(pos<=0 || pos >= lastPos)
10+
return -1;
11+
12+
return (int) (pos-1)/2;
13+
}
14+
15+
int getLeftChildPos(int pos, int lastPos)
16+
{
17+
int left = (2*pos) + 1;
18+
19+
if(left >= lastPos)
20+
return -1;
21+
22+
return left;
23+
}
24+
25+
int getRightChildPos(int pos, int lastPos)
26+
{
27+
int right = (2*pos) + 2;
28+
29+
if(right >= lastPos)
30+
return -1;
31+
32+
return right;
33+
}
34+
35+
int getMaximum(int heap[], int lastPos)
36+
{
37+
if(lastPos <= 0)
38+
return -1;
39+
40+
return heap[0];
41+
}
42+
43+
void swapElem(int heap[], int pos1, int pos2)
44+
{
45+
int tmp;
46+
47+
tmp = heap[pos1];
48+
heap[pos1] = heap[pos2];
49+
heap[pos2] = tmp;
50+
}
51+
52+
void heapifyDown(int heap[], int pos, int lastPos)
53+
{
54+
int heapSize = lastPos;
55+
while(1)
56+
{
57+
int left = getLeftChildPos(pos, heapSize);
58+
int right = getRightChildPos(pos, heapSize);
59+
int maxValPos;
60+
61+
if(left != -1 && heap[left] > heap[pos])
62+
maxValPos = left;
63+
else
64+
maxValPos = pos;
65+
66+
if(right != -1 && heap[right] > heap[maxValPos])
67+
maxValPos = right;
68+
69+
if(maxValPos != pos)
70+
{
71+
swapElem(heap, pos, maxValPos);
72+
}
73+
else
74+
break;
75+
76+
pos = maxValPos;
77+
}
78+
}
79+
80+
void heapifyUp(int heap[], int lastPos)
81+
{
82+
int pos = lastPos;
83+
while(pos>0)
84+
{
85+
int parent = getParentPos(pos, lastPos);
86+
if(parent == -1)
87+
break;
88+
89+
if(heap[parent] < heap[pos])
90+
{
91+
swapElem(heap, parent, pos);
92+
pos = parent;
93+
}
94+
else
95+
break;
96+
}
97+
}
98+
99+
100+
int main()
101+
{
102+
int heap[SZ];
103+
int value, num_of_elem = 0, action;
104+
105+
while(1)
106+
{
107+
printf("Enter Action: \n 1.Insert \n 2.Get Max Value \n 3.Exit\n");
108+
scanf("%d", &action);
109+
110+
if(action == 1) //Insertion
111+
{
112+
printf("Enter Value: ");
113+
scanf("%d", &value);
114+
heap[num_of_elem] = value;
115+
116+
heapifyUp(heap, num_of_elem);
117+
num_of_elem++;
118+
}
119+
else if(action == 2) //Get and Delete Max Value
120+
{
121+
if(num_of_elem <= 0)
122+
{
123+
printf("No Elements Available\n");
124+
continue;
125+
}
126+
127+
int maxVal = getMaximum(heap, num_of_elem);
128+
heap[0] = heap[num_of_elem - 1];
129+
130+
printf("Max Val: %d\n", maxVal);
131+
num_of_elem--;
132+
133+
heapifyDown(heap, 0, num_of_elem);
134+
}
135+
else
136+
break;
137+
}
138+
139+
return 0;
140+
}
357 KB
Binary file not shown.

Data Structure/Binary Heap/heap.bmp

384 KB
Binary file not shown.
105 KB
Loading
292 KB
Loading

0 commit comments

Comments
 (0)