0% found this document useful (0 votes)
1 views55 pages

UNIT-5 NOTES (1)

The document provides an overview of tree data structures, defining key terminology such as nodes, edges, root, parent, child, and leaf nodes. It describes various types of trees, including binary trees, binary search trees, and AVL trees, along with their representations and operations like insertion, searching, and deletion. Additionally, it covers tree traversals, detailing in-order, pre-order, and post-order methods for displaying tree nodes.

Uploaded by

vicky143244
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views55 pages

UNIT-5 NOTES (1)

The document provides an overview of tree data structures, defining key terminology such as nodes, edges, root, parent, child, and leaf nodes. It describes various types of trees, including binary trees, binary search trees, and AVL trees, along with their representations and operations like insertion, searching, and deletion. Additionally, it covers tree traversals, detailing in-order, pre-order, and post-order methods for displaying tree nodes.

Uploaded by

vicky143244
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 55

Unit_5

Tree - Terminology

In linear data structure data is organized in sequential order and in non-linear data structure data

is organized in random order. A tree is a very popular non-linear data structure used in a wide

range of applications. A tree data structure can be defined as follows...

Tree is a non-linear data structure which organizes data in hierarchical structure and this

is a recursive definition.

A tree data structure can also be defined as follows...

Tree data structure is a collection of data (Node) which is organized in hierarchical

structure recursively

In tree data structure, every individual element is called as Node. Node in a tree data structure

stores the actual data of that particular element and link to next element in hierarchical structure.

In a tree data structure, if we have N number of nodes then we can have a maximum of N-

1 number of links.

Example
Terminology

In a tree data structure, we use the following terminology...

1. Root

In a tree data structure, the first node is called as Root Node. Every tree must have a root node.

We can say that the root node is the origin of the tree data structure. In any tree, there must be

only one root node. We never have multiple root nodes in a tree.

2. Edge

In a tree data structure, the connecting link between any two nodes is called as EDGE. In a tree

with 'N' number of nodes there will be a maximum of 'N-1' number of edges.
3. Parent

In a tree data structure, the node which is a predecessor of any node is called as PARENT NODE.

In simple words, the node which has a branch from it to any other node is called a parent node.

Parent node can also be defined as "The node which has child / children".

4. Child

In a tree data structure, the node which is descendant of any node is called as CHILD Node. In

simple words, the node which has a link from its parent node is called as child node. In a tree, any

parent node can have any number of child nodes. In a tree, all the nodes except root are child

nodes.
5. Siblings

In a tree data structure, nodes which belong to same Parent are called as SIBLINGS. In simple

words, the nodes with the same parent are called Sibling nodes.

6. Leaf

In a tree data structure, the node which does not have a child is called as LEAF Node. In simple

words, a leaf is a node with no child.

In a tree data structure, the leaf nodes are also called as External Nodes. External node is also a

node with no child. In a tree, leaf node is also called as 'Terminal' node.
7. Internal Nodes

In a tree data structure, the node which has atleast one child is called as INTERNAL Node. In

simple words, an internal node is a node with atleast one child.

In a tree data structure, nodes other than leaf nodes are called as Internal Nodes. The root

node is also said to be Internal Node if the tree has more than one node. Internal nodes are

also called as 'Non-Terminal' nodes.

8. Degree

In a tree data structure, the total number of children of a node is called as DEGREE of that Node.

In simple words, the Degree of a node is total number of children it has. The highest degree of a

node among all the nodes in a tree is called as 'Degree of Tree'


9. Level

In a tree data structure, the root node is said to be at Level 0 and the children of root node are at

Level 1 and the children of the nodes which are at Level 1 will be at Level 2 and so on... In simple

words, in a tree each step from top to bottom is called as a Level and the Level count starts with

'0' and incremented by one at each level (Step).

10. Height

In a tree data structure, the total number of edges from leaf node to a particular node in the longest

path is called as HEIGHT of that Node. In a tree, height of the root node is said to be height of

the tree. In a tree, height of all leaf nodes is '0'.


11. Depth

In a tree data structure, the total number of egdes from root node to a particular node is called

as DEPTH of that Node. In a tree, the total number of edges from root node to a leaf node in the

longest path is said to be Depth of the tree. In simple words, the highest depth of any leaf node

in a tree is said to be depth of that tree. In a tree, depth of the root node is '0'.

12. Path

In a tree data structure, the sequence of Nodes and Edges from one node to another node is called

as PATH between that two Nodes. Length of a Path is total number of nodes in that path. In below

example the path A - B - E - J has length 4.


13. Sub Tree

In a tree data structure, each child from a node forms a subtree recursively. Every child node will

form a subtree on its parent node.

Types of Trees:

Trees are a fundamental data structure in computer


science, used to represent hierarchical relationships. This tutorial
covers several key types of trees.

Binary Trees: Each node has up to two children, the left child
node and the right child node. This structure is the foundation
for more complex tree types like Binay Search Trees and AVL
Trees.

Binary Search Trees (BSTs): A type of Binary Tree where for


each node, the left child node has a lower value, and the right
child node has a higher value.

AVL Trees: A type of Binary Search Tree that self-balances so


that for every node, the difference in height between the left and
right subtrees is at most one. This balance is maintained through
rotations when nodes are inserted or deleted.

Each of these data structures are described in detail on the next


pages, including animations and how to implement them.
Tree Representations
A binary tree data structure is represented using two methods. Those methods are as follows...

1. Array Representation

2. Linked List Representation

Consider the following binary tree...

1. Array Representation of Binary Tree

In array representation of a binary tree, we use one-dimensional array (1-D Array) to represent a

binary tree.

Consider the above example of a binary tree and it is represented as follows...

To represent a binary tree of depth 'n' using array representation, we need one dimensional array

with a maximum size of 2n + 1.

2. Linked List Representation of Binary Tree

We use a double linked list to represent a binary tree. In a double linked list, every node consists

of three fields. First field for storing left child address, second for storing actual data and third for

storing right child address.

In this linked list representation, a node has the following structure...


The above example of the binary tree represented using Linked list representation is shown as

follows...

Binary Search tree?


A binary search tree follows some order to arrange
the elements. In a Binary search tree, the value of left node must be smaller than the
parent node, and the value of right node must be greater than the parent node. This
rule is applied recursively to the left and right subtrees of the root.

Let's understand the concept of Binary search tree with an example.

In the above figure, we can observe that the root node is 40, and all the nodes of the
left subtree are smaller than the root node, and all the nodes of the right subtree are
greater than the root node.

Similarly, we can see the left child of root node is greater than its left child and smaller
than its right child. So, it also satisfies the property of binary search tree. Therefore, we
can say that the tree in the above image is a binary search tree.
Suppose if we change the value of node 35 to 55 in the above tree, check whether the
tree will be binary search tree or not.

In the above tree, the value of root node is 40, which is greater than its left child 30
but smaller than right child of 30, i.e., 55. So, the above tree does not satisfy the
property of Binary search tree. Therefore, the above tree is not a binary search tree.

Advantages of Binary search tree

o Searching an element in the Binary search tree is easy as we always have a hint that
which subtree has the desired element.
o As compared to array and linked lists, insertion and deletion operations are faster in
BST.

Insertion Operation in BST


In a binary search tree, the insertion operation is performed with O(log n) time complexity. In binary
search tree, new node is always inserted as a leaf node. The insertion operation is performed as
follows...

 Step 1 - Create a newNode with given value and set its left and right to NULL.
 Step 2 - Check whether tree is Empty.
 Step 3 - If the tree is Empty, then set root to newNode.
 Step 4 - If the tree is Not Empty, then check whether the value of newNode
is smaller or larger than the node (here it is root node).
 Step 5 - If newNode is smaller than or equal to the node then move to its left child. If
newNode is larger than the node then move to its right child.
 Step 6- Repeat the above steps until we reach to the leaf node (i.e., reaches to NULL).
 Step 7 - After reaching the leaf node, insert the newNode as left child if the newNode
is smaller or equal to that leaf node or else insert it as right child.

Example of creating a binary search tree


Now, let's see the creation of binary search tree using an example.

Suppose the data elements are - 45, 15, 79, 90, 10, 55, 12, 20, 50

o First, we have to insert 45 into the tree as the root of the tree.
o Then, read the next element; if it is smaller than the root node, insert it as the root of
the left subtree, and move to the next element.
o Otherwise, if the element is larger than the root node, then insert it as the root of the
right subtree.
Now, let's see the process of creating the Binary search tree using the given data
element. The process of creating the BST is shown below -

Step 1 - Insert 45.

Step 2 - Insert 15.

As 15 is smaller than 45, so insert it as the root node of the left subtree.

Step 3 - Insert 79.

As 79 is greater than 45, so insert it as the root node of the right subtree.
Step 4 - Insert 90.

90 is greater than 45 and 79, so it will be inserted as the right subtree of 79.

Step 5 - Insert 10.

10 is smaller than 45 and 15, so it will be inserted as a left subtree of 15.

Step 6 - Insert 55.

55 is larger than 45 and smaller than 79, so it will be inserted as the left subtree of 79.
Step 7 - Insert 12.

12 is smaller than 45 and 15 but greater than 10, so it will be inserted as the right
subtree of 10.

Step 8 - Insert 20.

20 is smaller than 45 but greater than 15, so it will be inserted as the right subtree of
15.
Step 9 - Insert 50.

50 is greater than 45 but smaller than 79 and 55. So, it will be inserted as a left subtree
of 55.
2. Searching in Binary search tree
Searching means to find or locate a specific element or node in a data structure. In
Binary search tree, searching a node is easy because elements in BST are stored in a
specific order. The steps of searching a node in Binary Search tree are listed as follows
- First, compare the element to be searched with the root element of the tree.

1. If root is matched with the target element, then return the node's location.
2. If it is not matched, then check whether the item is less than the root element, if it is
smaller than the root element, then move to the left subtree.
3. If it is larger than the root element, then move to the right subtree.
4. Repeat the above procedure recursively until the match is found.
5. If the element is not found or not present in the tree, then return NULL.

Now, let's understand the searching in binary tree using an example. We are taking the
binary search tree formed above. Suppose we have to find node 20 from the below tree.

Step1:

Step2:
Step3:

3. Deletion in Binary Search tree

In a binary search tree, we must delete a node from the tree


by keeping in mind that the property of BST is not violated. To delete a node from BST,
there are three possible situations occur -

o The node to be deleted is the leaf node, or,


o The node to be deleted has only one child, and,
o The node to be deleted has two children
We will understand the situations listed above in detail.

When the node to be deleted is the leaf node

It is the simplest case to delete a node in BST. Here, we have to replace the leaf node
with NULL and simply free the allocated space.

We can see the process to delete a leaf node from BST in the below image. In below
image, suppose we have to delete node 90, as the node to be deleted is a leaf node,
so it will be replaced with NULL, and the allocated space will free.
When the node to be deleted has only one child

In this case, we have to replace the target node with its child, and then delete the child
node. It means that after replacing the target node with its child node, the child node
will now contain the value to be deleted. So, we simply have to replace the child node
with NULL and free up the allocated space.

We can see the process of deleting a node with one child from BST in the below image.
In the below image, suppose we have to delete the node 79, as the node to be deleted
has only one child, so it will be replaced with its child 55.

So, the replaced node 79 will now be a leaf node that can be easily deleted.

When the node to be deleted has two children

This case of deleting a node in BST is a bit complex among other two cases. In such a
case, the steps to be followed are listed as follows -

o First, find the inorder successor of the node to be deleted.


o After that, replace that node with the inorder successor until the target node is placed
at the leaf of tree.
o And at last, replace the node with NULL and free up the allocated space.
The inorder successor is required when the right child of the node is not empty. We
can obtain the inorder successor by finding the minimum element in the right child of
the node.

We can see the process of deleting a node with two children from BST in the below
image. In the below image, suppose we have to delete node 45 that is the root node,
as the node to be deleted has two children, so it will be replaced with its inorder
successor. Now, node 45 will be at the leaf of the tree so that it can be deleted easily.

Example
Construct a Binary Search Tree by inserting the following sequence of numbers...

10,12,5,4,20,8,7,15 and 13
Above elements are inserted into a Binary Search Tree as follows...
Tree Traversals:

Binary Tree Traversals


When we wanted to display a binary tree, we need to follow some order in which all the nodes of

that binary tree must be displayed. In any binary tree, displaying order of nodes depends on the

traversal method.

Displaying (or) visiting order of nodes in a binary tree is called as Binary Tree Traversal.
There are three types of binary tree traversals.

1. In - Order Traversal

2. Pre - Order Traversal

3. Post - Order Traversal

1. In-order Traversal(LEFT,ROOT,RIGHT)

In this traversal method, the left subtree is visited first, then the root and later
the right sub-tree. We should always remember that every node may represent a
subtree itself.
If a binary tree is traversed in-order, the output will produce sorted key values
in an ascending order.

We start from A, and following in-order traversal, we move to its left subtree
B.B is also traversed in-order. The process goes on until all the nodes are visited.
The output of in-order traversal of this tree will be −
DBEAFCG
2. Pre-order Traversal(ROOT,LEFT,RIGHT)
In this traversal method, the root node is visited first, then the left subtree and
finally the right subtree.

We start from A, and following pre-order traversal, we first visit itself and
B A
then move to its left subtree B. is also traversed pre-order. The process goes

on until all the nodes are visited. The output of pre-order traversal of this tree
will be −
A→B→D→E→C→F→G

3. Post-order Traversal(LEFT,RIGHT,ROOT)
In this traversal method, the root node is visited last, hence the name. First we
traverse the left subtree, then the right subtree and finally the root node.
We start from A, and following pre-order traversal, we first visit the left
subtree B. B is also traversed post-order. The process goes on until all the nodes

are visited. The output of post-order traversal of this tree will be


D→E→B→F→G→C→A

TYPES OF TRAVERSAL (EXAMPLE-2)

1. In order traversal visits the node in the order:


In order(tree )
● Traverse the left subtree, i.e., call Inorder(left->subtree)
● Visit the root.
● Traverse the right subtree, i.e., call Inorder(right->subtree)
2. Pre order traversal visits the node in the order:
Pre order(tree)
● Visit the root.
● Traverse the left subtree, i.e., call Preorder(left->subtree)
● Traverse the right subtree, i.e., call Preorder(right->subtree)
3. Postorder traversal visits the node in the order:
●Traverse the left subtree, i.e., call Postorder(left->subtree)
● Traverse the right subtree, i.e., call Postorder(right->subtree)
● Visit the root
EXAMPLE-3:
UNIT-5 (GRAPHS)

Introduction to Graph
Graph is a non-linear data structure. It contains a set of points known as nodes (or vertices) and a set of links

known as edges (or Arcs). Here edges are used to connect the vertices. A graph is defined as follows...

Graph is a collection of vertices and arcs in which vertices are connected with arcs

OR

Graph is a collection of nodes and edges in which nodes are connected with edges

Generally, a graph G is represented as G = ( V , E ), where V is set of vertices and E is set of edges.

Example

The following is a graph with 5 vertices and 6 edges.

This graph G can be defined as G = ( V , E ) Where

V = {A,B,C,D,E} and E = {(A,B),(A,C)(A,D),(B,D),(C,D),(B,E),(E,D)}.

Graph Terminology

We use the following terms in graph data structure...

Vertex

Individual data element of a graph is called as Vertex. Vertex is also known as node. In above example graph, A,

B, C, D & E are known as vertices.

Edge
An edge is a connecting link between two vertices. Edge is also known as Arc. An edge is represented as

(startingVertex, endingVertex). For example, in above graph the link between vertices A and B is represented as

(A,B). In above example graph, there are 7 edges (i.e., (A,B), (A,C), (A,D), (B,D), (B,E), (C,D), (D,E)).

Edges are three types.

1. Undirected Edge - An undirected egde is a bidirectional edge. If there is undirected edge between vertices

A and B then edge (A , B) is equal to edge (B , A).

2. Directed Edge - A directed egde is a unidirectional edge. If there is directed edge between vertices A and

B then edge (A , B) is not equal to edge (B , A).

3. Weighted Edge - A weighted egde is a edge with value (cost) on it.

Undirected Graph

A graph with only undirected edges is said to be undirected graph.

Directed Graph

A graph with only directed edges is said to be directed graph.

Mixed Graph

A graph with both undirected and directed edges is said to be mixed graph.

End vertices or Endpoints

The two vertices joined by edge are called end vertices (or endpoints) of that edge.

Origin

If a edge is directed, its first endpoint is said to be the origin of it.

Destination

If a edge is directed, its first endpoint is said to be the origin of it and the other endpoint is said to be the destination

of that edge.

Adjacent

If there is an edge between vertices A and B then both A and B are said to be adjacent. In other words, vertices A

and B are said to be adjacent if there is an edge between them.

Incident
Edge is said to be incident on a vertex if the vertex is one of the endpoints of that edge.

Outgoing Edge

A directed edge is said to be outgoing edge on its origin vertex.

Incoming Edge

A directed edge is said to be incoming edge on its destination vertex.

Degree

Total number of edges connected to a vertex is said to be degree of that vertex.

Indegree

Total number of incoming edges connected to a vertex is said to be indegree of that vertex.

Outdegree

Total number of outgoing edges connected to a vertex is said to be outdegree of that vertex.

Parallel edges or Multiple edges

If there are two undirected edges with same end vertices and two directed edges with same origin and destination,

such edges are called parallel edges or multiple edges.

Self-loop

Edge (undirected or directed) is a self-loop if its two endpoints coincide with each other.

Simple Graph

A graph is said to be simple if there are no parallel and self-loop edges.

Path

A path is a sequence of alternate vertices and edges that starts at a vertex and ends at other vertex such that

each edge is incident to its predecessor and successor vertex.


Graph Representations
Graph data structure is represented using following representations...

1. Adjacency Matrix

2. Incidence Matrix

3. Adjacency List

Adjacency Matrix

In this representation, the graph is represented using a matrix of size total number of vertices by a total number of

vertices. That means a graph with 4 vertices is represented using a matrix of size 4X4. In this matrix, both rows

and columns represent vertices. This matrix is filled with either 1 or 0. Here, 1 represents that there is an edge

from row vertex to column vertex and 0 represents that there is no edge from row vertex to column vertex.

For example, consider the following undirected graph representation...

Directed graph representation...

Incidence Matrix

In this representation, the graph is represented using a matrix of size total number of vertices by a total number of

edges. That means graph with 4 vertices and 6 edges is represented using a matrix of size 4X6. In this matrix,

rows represent vertices and columns represents edges. This matrix is filled with 0 or 1 or -1. Here, 0 represents
that the row edge is not connected to column vertex, 1 represents that the row edge is connected as the outgoing

edge to column vertex and -1 represents that the row edge is connected as the incoming edge to column vertex.

For example, consider the following directed graph representation...

Adjacency List

In this representation, every vertex of a graph contains list of its adjacent vertices.

For example, consider the following directed graph representation implemented using linked list...

This representation can also be implemented using an array as follows..


Graph Traversal - DFS
Graph traversal is a technique used for a searching vertex in a graph. The graph traversal is also used to

decide the order of vertices is visited in the search process. A graph traversal finds the edges to be used in the

search process without creating loops. That means using graph traversal we visit all the vertices of the graph

without getting into looping path.

There are two graph traversal techniques and they are as follows...

1. DFS (Depth First Search)

2. BFS (Breadth First Search)

DFS (Depth First Search)

DFS traversal of a graph produces a spanning tree as final result. Spanning Tree is a graph without loops. We

use Stack data structure with maximum size of total number of vertices in the graph to implement DFS

traversal.

We use the following steps to implement DFS traversal...

 Step 1 - Define a Stack of size total number of vertices in the graph.

 Step 2 - Select any vertex as starting point for traversal. Visit that vertex and push it on to the Stack.

 Step 3 - Visit any one of the non-visited adjacent vertices of a vertex which is at the top of stack and push

it on to the stack.

 Step 4 - Repeat step 3 until there is no new vertex to be visited from the vertex which is at the top of the

stack.

 Step 5 - When there is no new vertex to visit then use back tracking and pop one vertex from the stack.

 Step 6 - Repeat steps 3, 4 and 5 until stack becomes Empty.

 Step 7 - When stack becomes Empty, then produce final spanning tree by removing unused edges from

the graph

Back tracking is coming back to the vertex from which we reached the current vertex.
Example
2. BFS (Breadth First Search)
BFS traversal of a graph produces a spanning tree as final
result. Spanning Tree is a graph without loops. We use Queue data structure with
maximum size of total number of vertices in the graph to implement BFS traversal.

We use the following steps to implement BFS traversal...

 Step 1 - Define a Queue of size total number of vertices in the graph.


 Step 2 - Select any vertex as starting point for traversal. Visit that vertex and
insert it into the Queue.
 Step 3 - Visit all the non-visited adjacent vertices of the vertex which is at front
of the Queue and insert them into the Queue.
 Step 4 - When there is no new vertex to be visited from the vertex which is at
front of the Queue then delete that vertex.
 Step 5 - Repeat steps 3 and 4 until queue becomes empty.
 Step 6 - When queue becomes empty, then produce final spanning tree by
removing unused edges from the graph

Example
Difference between BFS and DFS:
The following are the important differences between BFS and DFS

Key BFS DFS

BFS stands for Breadth First


Definition DFS stands for Depth First Search.
Search.

Data
BFS uses a Queue to find
structure DFS uses a Stack to find the shortest path.
the shortest path.

Source BFS is better when target is


DFS is better when target is far from source.
closer to Source.

As BFS considers all


DFS is more suitable for decision tree. As with
Suitability for neighbor so it is not suitable
one decision, we need to traverse further to augment the
decision tree for decision tree used in
decision. If we reach the conclusion, we won.
puzzle games.

Speed BFS is slower than DFS. DFS is faster than BFS.

Time Complexity of BFS =


Time Time Complexity of DFS is also O(V+E) where
O(V+E) where V is vertices
Complexity V is vertices and E is edges.
and E is edges.

BFS requires more memory


Memory DFS requires less memory space.
space.

Tapping in In BFS, there is no problem


In DFS, we may be trapped into infinite loops.
loops of trapping into finite loops.

BFS is implemented using


DFS is implemented using LIFO (Last In First Out)
Principle FIFO (First In First Out)
principle.
principle.
BFS AND DFS USING IN TREE

………………………………………………………****GRAPHS****……………………………………………………………………………………………
INTRODUCTION TO HASHING

Hashing is a popular technique in computer science


that involves mapping large data sets to fixed-length values. It is a process of
converting a data set of variable size into a data set of a fixed size. The ability to
perform efficient lookup operations makes hashing an essential concept in data
structures.
What is Hashing?
Hashing is defined as follows...

Hashing is the process of indexing and retrieving element (data) in a data structure to
provide a faster way of finding the element using a hash key.

Hashing is commonly used to create a unique identifier for a piece


of data, which can be used to quickly look up that data in a large dataset. For
example, a web browser may use hashing to store website passwords securely. When
a user enters their password, the browser converts it into a hash value and compares
it to the stored hash value to authenticate the user.

How Hashing Works?


The process of hashing can be broken down into three steps:

o Input: The data to be hashed is input into the hashing algorithm.


o Hash Function: The hashing algorithm takes the input data and applies a
mathematical function to generate a fixed-size hash value. The hash function
should be designed so that different input values produce different hash values,
and small changes in the input produce large changes in the output.
o Output: The hash value is returned, which is used as an index to store or retrieve
data in a data structure.
Hash Functions:
Hash Function: A hash function is a type of mathematical operation
that takes an input (or key) and outputs a fixed-size result known as a hash code or
hash value. The hash function must always yield the same hash code for the same input
in order to be deterministic.

Additionally, the hash function should produce a unique hash code for each input,
which is known as the hash property.

Types of Hash functions


There are many hash functions that use numeric or alphanumeric keys. This article focuses on discussing
different hash functions:
1. Division Method.
2. Mid Square Method.
3. Folding Method.
4. Multiplication Method.
Let’s begin discussing these methods in detail.

1. Division Method:
This is the most simple and easiest method to generate a hash value. The hash function divides the value k
by M and then uses the remainder obtained.
Formula:
h(K) = k mod M
Here,
k is the key value, and
M is the size of the hash table.

It is best suited that M is a prime number as that can make sure the keys are more uniformly distributed.
The hash function is dependent upon the remainder of a division.
Example:
k = 12345
M = 95
h(12345) = 12345 mod 95
= 90
k = 1276
M = 11
h(1276) = 1276 mod 11
=0

2. Mid Square Method:


The mid-square method is a very good hashing method. It involves two
steps to compute the hash value-
1. Square the value of the key k i.e. k2
2. Extract the middle r digits as the hash value.
Formula:
h(K) = h(k x k)
Here,
k is the key value.

The value of r can be decided based on the size of the table.


Example:
Suppose the hash table has 100 memory locations. So r = 2 because two digits are required to map the key
to the memory location.
k = 60
k x k = 60 x 60
= 3600
h(60) = 60
The hash value obtained is 60

3. Digit Folding Method:

This method involves two steps:


1. Divide the key-value k into a number of parts i.e. k1, k2, k3,….,kn, where each part has the same
number of digits except for the last part that can have lesser digits than the other parts.
2. Add the individual parts. The hash value is obtained by ignoring the last carry if any.
Formula:
k = k1, k2, k3, k4, ….., kn
s = k1+ k2 + k3 + k4 +….+ kn
h(K)= s
Here,
s is obtained by adding the parts of the key k

Example:
k = 12345
k1 = 12, k2 = 34, k3 = 5
s = k1 + k2 + k3
= 12 + 34 + 5
= 51
h(K) = 51

Note:
The number of digits in each part varies depending upon the size of the hash table. Suppose for example
the size of the hash table is 100, then each part must have two digits except for the last part which can have
a lesser number of digits.

4. Multiplication Method
This method involves the following steps:
1. Choose a constant value A such that 0 < A < 1.
2. Multiply the key value with A.
3. Extract the fractional part of kA.
4. Multiply the result of the above step by the size of the hash table i.e. M.
5. The resulting hash value is obtained by taking the floor of the result obtained in step 4.
Formula:
h(K) = floor (M (kA mod 1))
Here,
M is the size of the hash table.
k is the key value.
A is a constant value.

Example:
k = 12345
A = 0.357840
M = 100
h(12345) = floor[ 100 (12345*0.357840 mod 1)]
= floor[ 100 (4417.5348 mod 1) ]
= floor[ 100 (0.5348) ]
= floor[ 53.48 ]
= 53

Collision Resolution Techniques:

In Hashing, hash functions were used to generate hash


values. The hash value is used to create an Index for the keys in the
hash table. The hash function may return the same hash value for two
or more keys. When two or more keys have the same hash value,
a collision happens. To handle this collision, we use Collision
Resolution Techniques.
1.Separate Chaining is to make each cell of the hash table point to a linked list of records that
have the same hash function value. Chaining is simple but requires additional memory outside the
table.

example: We have given a hash function and we have to insert some elements in the hash table
using a separate chaining method for collision resolution technique.

Hash function = key % 5,


Elements = 12, 15, 22, 25 and 37.

Let’s see step by step approach to how to solve the above problem:
2) Open Addressing
In open addressing, all elements are stored in the hash table
itself. Each table entry contains either a record or NIL. When searching for an
element, we examine the table slots one by one until the desired element is found
or it is clear that the element is not in the table.
……………..UNIT-5 ……………

You might also like