17
Experiment No: 4 Name of the Experiment: To implement operations on binary heap Aim: To implement operations on binary heap Hardware Software Requirements: Intel based desktop PC Minimum of 166 MHZ or Faster processor At least 256 MB Ram At least 512 MB hard-disk with at least 100 MB free of disk place C Compiler (Turbo-c) or C++ Compiler (Turbo-C++) Description: A binary heap is a heap data structure created using a binary tree. It can be seen as a binary tree with two additional constraints: Shape property The tree is a complete binary tree; that is, all levels of the tree, except possibly the last one (deepest) are fully filled, and, if the last level of the tree is not complete, the nodes of that level are filled from left to right. Heap property All nodes are either [greater than or equal to] or [less than or equal to] each of its children, according to a comparison predicate defined for the heap. The heap ordering property can be one of two types: the 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.

Web viewTo make sure that the hole appears at the last node, we render the deletion to an insertion in top-down direction

Embed Size (px)

Citation preview

Page 1: Web viewTo make sure that the hole appears at the last node, we render the deletion to an insertion in top-down direction

Experiment No: 4

Name of the Experiment: To implement operations on binary heap

Aim: To implement operations on binary heap

Hardware Software Requirements:

Intel based desktop PC

Minimum of 166 MHZ or Faster processor

At least 256 MB Ram

At least 512 MB hard-disk with at least 100 MB free of disk place

C Compiler (Turbo-c) or C++ Compiler (Turbo-C++)

Description:

A binary heap is a heap data structure created using a binary tree. It can be seen as a binary tree with two additional constraints:

Shape propertyThe tree is a complete binary tree; that is, all levels of the tree, except possibly the last one (deepest) are fully filled, and, if the last level of the tree is not complete, the nodes of that level are filled from left to right.

Heap property All nodes are either [greater than or equal to] or [less than or equal to] each of

its children, according to a comparison predicate defined for the heap.

The heap ordering property can be one of two types:

the 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.

the 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.

Page 2: Web viewTo make sure that the hole appears at the last node, we render the deletion to an insertion in top-down direction

Since the ordering of siblings in a heap is not specified by the heap property, a single node's two children can be freely interchanged unless doing so violates the shape property (compare with treap). The binary heap is a special case of the d-ary heap in which d = 2.

Since a heap is a complete binary tree, the elements can be conveniently stored in an array. If an element is at position i in the array, then the left child will be in position 2i and the right child will be in position 2i + 1. By the same token, a non-root element at

position i will have its parent at position     Because of its structure, a heap with height k will have between 2kand 2k + 1 - 1

elements. Therefore a heap with n elements will have height =  Because of the heap property, the minimum element will always be present at the root

of the heap. Thus the find min operation will have worst-case O (1) running time.

The tree below is a Complete Binary Heap Tree:

Since the tree is complete, we use the following array implementation:

Given array A:

A(1) - contains the root The node in A(i) has its left child in A(2*i), its right child in A(2*i+1),  and its parent in A([i/2]). The smallest element is always at the root, thus the access time 

to the element with highest priority is constant O(1).

6 10 12 15 17 21 23 20 19 34  

This is the array that implements the binary heap in the example. The nodes of the tree are written in the array level by level from left to right. The first element in the

Page 3: Web viewTo make sure that the hole appears at the last node, we render the deletion to an insertion in top-down direction

array is 6 - this is the node at level 0. Then come 10 and 12 - the nodes at level1. Further we have 15, 17 (children of 10), then 18 and 23 (children of 12) - all at level2. Finally we have 20, 19 and 34 - the nodes at the last level.

Let's take a node in the array and find its parent and its children.

Consider for example 17. 

Its position in the array is 5. Its parent 12 is at position [5/2] = 2 Its left child is at position 5*2 = 10, this is the element 34,  and its right child is at position 2*5 + 1 = 11, (still empty).

Insert a node - percolate up

A hole is created at the bottom of the tree, in the next available position.

If the new node has a greater value than the parent of the hole - we insert the node in the hole.Thus, if the new value to be inserted is 18, our new binary heap would be:

Page 4: Web viewTo make sure that the hole appears at the last node, we render the deletion to an insertion in top-down direction

If the new value is less than its parent, we slide down the parent of the hole, so the hole moves up, and check to see if the new node is less than the parent of the new hole. This process is repeated until we find a place for the new node, possibly at the very root of the binary heap.

Let's say we want to insert 16. 16 is less than 17, so we slide down 17, and the hole appears at the node where 17 used to be:

Since 16 is less than 10, we can insert it in the hole:

Page 5: Web viewTo make sure that the hole appears at the last node, we render the deletion to an insertion in top-down direction

Complexity of insertion:

O(logN) in the worst case.  To insert a node in the worst case we would need to percolate up to the root of the binary heap tree. Since the tree is a complete tree, the longest path from the bottom to the top is not longer than O(logN), where N is the number of nodes in the tree. Hence we would do no more than O(logN) percolations up.

Deleting a node - percolate down

We delete the node at the root - this is the node with highest priority. After deleting there is a hole at the root, which has to be filled.

We may think of sliding the "hole" down and moving up the smaller of the children of the "hole", and repeat this until the hole gets to the bottom. The hole may appear anywhere at the bottom, and if it is not at the last node, the tree is not anymore a complete binary tree. (You may try this approach on the tree below and see what happens with the tree.)

To make sure that the hole appears at the last node, we render the deletion to an insertion in top-down direction. We can try to insert in the hole the last element that has been inserted, i.e. the rightmost element in the lowest row (the last element in the array). Thus in the array the last element will become empty, and the tree will be complete.

Page 6: Web viewTo make sure that the hole appears at the last node, we render the deletion to an insertion in top-down direction

The last element in the example is 18. The hole is at the root .

 

Most certainly, 18 will not fit there, and we have to percolate the hole down The left child of the hole is with higher priority than the right one. We slide the hole down to the left:

Still, 18 does not fit in the new hole, it has lower priority than its children 15 and 17. The left child of the hole is with higher priority than the right one. We slide the hole down to the left:

Now 18 fits the hole and we can safely insert it there:

Page 7: Web viewTo make sure that the hole appears at the last node, we render the deletion to an insertion in top-down direction

Complexity of deletion:

O(logN) in the worst case. We always delete from the top, hence the time to access the element with highest priority is a constant. However, after deletion we have to fill in the hole at the root. In the worst case we will percolate down to the bottom. Since the hight of the tree is O(logN), where N is the number of nodes, the worst running time is O(logN).

Creating HeapGiven a set of n elements, the problem here is to create a heap of these elements.

obvious approach is to insert the n elements, one at a time, into an initially empty heap. Since the worstcase complexity of inserts is O (log n), this approach has a worstcase running time of O ( n log n)

Another approach, purposed by Floyd in 1964, is to use a procedure called ``pushdown'' repeatedly, starting with the array consisting of the given n elements in the input-order.

o The function pushdown (first, last) assumes that the elements a[first], ..., a[last] obey the heap property, except possibly the children of a[first]. The function pushes down a[first] until the heap property violation is stopped.

o The following code will accomplish what is required:

Below Figure shows an example of this for an array [5 9 4 2 1 6]

The worst-case complexity of this approach can be shown to b O (n) by virtue of the following result.

Figure : Creation of heap

Page 8: Web viewTo make sure that the hole appears at the last node, we render the deletion to an insertion in top-down direction
Page 9: Web viewTo make sure that the hole appears at the last node, we render the deletion to an insertion in top-down direction

PROGRAM:

#include <stdio.h> #include <stdlib.h>

#define HEAPCOUNT 100

int count = 0;

/* * find the smallest among the left(data[pos]) and * right child(data[pos + 1]). Check whether the smallest * among them is lesser than their parent. If so, swap * parent and the node with smallest value. Continue the * above processing from index "low" to "count" * 40 * / \ * 10 30 * 10 is smaller tha 30. 10 is comapared with its parent * and it is smaller(10 < 40). So, swap parent and 10. * 10 * / \ * 40 30 */ void insertHeap(int *data, int low, int count) { int pos = (2 * low) + 1, current = data[low]; while (pos <= count) { if (pos < count && data[pos] > data[pos + 1]) pos++; if (current <= data[pos]) break; else { data[low] = data[pos]; low = pos; pos = (2 * low) + 1; } } data[low] = current; return; }

/* * To construct a heap we always consider the * nodes which are present above the leaf. Here, * nodes present after data[n/2 - 1] are leaf nodes * insertHeap() - used for restoring the heap * data - holds node values & n - node count */ void buildHeap(int *data, int n) { int low;

Page 10: Web viewTo make sure that the hole appears at the last node, we render the deletion to an insertion in top-down direction

for (low = n/2 - 1; low >= 0; low--) { insertHeap(data, low, n-1); } return; }

void buildUp(int *data, int index) { int val = data[index]; /* if parent of the current node has value * greater than its child, then swap parent * and child nodes. Traverse up the tree * until u hit a condition where parent node * is having lesser value than children */ while (data[(index - 1) / 2] >= val) { data[index] = data[(index - 1) / 2]; if (!index) break; index = (index - 1) / 2; } data[index] = val; return; }

/* adding new node to the binary heap */ void addNode(int *data, int val, int n) { data[n] = val; buildUp(data, n); return; }

/* delete a node from binary heap */ void deleteNode(int *data, int n) { int val = data[0]; data[0] = data[n]; insertHeap(data, 0, n - 1); printf("%d is deleted from the heap\n", val); return; }

/* replacing root node with value val */ void replaceNode(int *data, int val, int n) { int i; data[0] = val; for (i = n/2 - 1; i >= 0; i--) insertHeap(data, i, n - 1); return; }

void display(int *data, int n) {

Page 11: Web viewTo make sure that the hole appears at the last node, we render the deletion to an insertion in top-down direction

int i; printf("\nData in Binary Heap:\n"); for (i = 0; i <= n; i++) { printf("%d ", data[i]); } printf("\n\n"); }

int main() { int n, i, *data, temp, ch, val; data = (int *)malloc(sizeof(int) * HEAPCOUNT); printf("Enter the no of elements(1-80):"); scanf("%d", &n);

if (n < 1 || n > 80) { printf("Threshold Exceeded!!\n"); return 0; }

for (i = 0; i < n; i++) { printf("Input %d:", i + 1); scanf("%d", &data[i]); count++; }

buildHeap(data, n); while (n < (HEAPCOUNT -1)) { printf("1. Add New Node\t2. Delete Node\n"); printf("3. Replace Node\t4. Display Heap\n"); printf("5. Exit\nEnter your choice:"); scanf("%d", &ch);

switch(ch) { case 1: printf("Enter your input:"); scanf("%d", &val); addNode(data, val, n); n++; break; case 2: deleteNode(data, n -1); n--; break; case 3: printf("Enter input value:"); scanf("%d", &val); replaceNode(data, val, n); break; case 4: display(data, n - 1);

Page 12: Web viewTo make sure that the hole appears at the last node, we render the deletion to an insertion in top-down direction

break; case 5: goto sort;

default: printf("Wrong Option!!\n"); break; }

} sort: /* swap root and current last node, then perform * restore heap to get data in sorted order. Basically, * we are performing insort operation. */ for (i = n - 1; i > 0; i--) { temp = data[i]; data[i] = data[0]; data[0] = temp; insertHeap(data, 0, i - 1); } printf("Sorted Data:\n"); for (i = 0; i < n; i++) printf("%d ", data[i]); printf("\n"); return 0; }

Page 13: Web viewTo make sure that the hole appears at the last node, we render the deletion to an insertion in top-down direction

OUTPUT: BINARY HEAP:

Enter the no of elements(1-80):10Input 1:6Input 2:10Input 3:12Input 4:15Input 5:17Input 6:21Input 7:23Input 8:20Input 9:19Input 10:341. Add New Node 2. Delete Node3. Replace Node 4. Display Heap5. ExitEnter your choice:

Enter your choice:4

Data in Binary Heap:6 10 12 15 17 21 23 20 19 34

1. Add New Node 2. Delete Node3. Replace Node 4. Display Heap5. ExitEnter your choice:

Enter your choice: 1Enter your input:181. Add New Node 2. Delete Node3. Replace Node 4. Display Heap5. ExitEnter your choice:

Enter your choice: 4

Data in Binary Heap:6 10 12 15 17 21 23 20 19 34 18

1. Add New Node 2. Delete Node3. Replace Node 4. Display Heap5. ExitEnter your choice:

Enter your choice:26 is deleted from the heap1. Add New Node 2. Delete Node3. Replace Node 4. Display Heap5. ExitEnter your choice:

Enter your choice: 4

Data in Binary Heap:10 15 12 18 17 21 23 20 19 34

1. Add New Node 2. Delete Node3. Replace Node 4. Display Heap5. Exit

Enter your choice:

Enter your choice: 1Enter your input:61. Add New Node 2. Delete Node3. Replace Node 4. Display Heap5. Exit

Enter your choice:4

Data in Binary Heap:6 10 12 18 15 21 23 20 19 34 17

1. Add New Node 2. Delete Node3. Replace Node 4. Display Heap5. ExitEnter your choice:

Enter your choice:5