Download as pdf or txt
Download as pdf or txt
You are on page 1of 146

Data Structure & Algorithm Lab (PCCCS307P)

S. B. JAIN INSTITUTE OF TECHNOLOGY,


MANAGEMENT & RESEARCH, NAGPUR.
Session 2024-25

LAB MANUAL
Data Structure & Algorithm Lab (N-PCCCS302P)

Year: 2nd
Semester: III

Name of Student:
Roll No.:
Semester/Year:
Academic Session:
Date of Performance:
Date of Submission:

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

Hardware and Software Requirement

Hardware Requirement
• Processor : Dual Core
• RAM : 1GB
• Hard Disk Drive : > 80 GB

Software Requirement
• Operating System – Windows 2007 and above
• IDE – Dev C++
• Online Platform: www.onlineGDB.com

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

Institute Vision:
Emerge as a leading Institute for developing competent and creative Professionals

Institute Mission:
1. Providing Quality Infrastructure and experienced faculty for academic excellence
2. Inculcating skills, knowledge and opportunities for competency and creativity
3. Aligning with Industries for knowledge sharing, research and development

Department Vision:
To become a center for quality education in the field of computer science & engineering and
to create competent professionals.

Department Mission:
• To provide academic ambience and latest software tools to prepare competent Software
Engineers with strong theoretical and practical knowledge.
• To foster professionalism and strong work ethics in students for the betterment of
Society.
• To provide adequate infrastructure as well as experienced & skilled faculty members.
• To encourage the spirit of entrepreneurship and adaptability in our students in view of
the ever-changing scenario of the Software Industry.

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

Course Outcomes:
On successful completion of this course, students will be able to
CO1 Apply: Apply appropriate abstract data type to solve basic computational problems.
CO2 Apply: Apply appropriate searching and sorting techniques for a given problem statement.
CO3 Evaluate: Choose appropriate data structures to solve given problems efficiently.
CO4 Create: Design applications using linear and nonlinear data structures with suitable
algorithms.

GENERAL INSTRUCTIONS FOR STUDENTS

DO’S
• Students should enter into the laboratory on time and should take permission before
entering laboratory.
• Students should come in proper uniforms.
• Students should come with Observation book and Lab manual in the laboratory.
• Students should maintain silence inside the laboratory.
• After completing the laboratory exercise, make sure to shut down the system and
arrange chairs properly.

DONT’S
• Students bringing the bags inside the laboratory.
• Students using mobile phones inside the laboratory.
• Students using the computers in an improper way.
• Students scribbling on the desk and mishandling the chairs.
• Students making noise inside the laboratory.

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

List of Practical’s

Sr. Name of Practical CO


No.
Pre- Develop a program to manage inventory of items in a store. Store information- --
Lab: Product Name, Product Code, Category and Unit Price using structure. Create
a dynamic array of structure for various inventory items and implement
functions using pointers to:

a) Add new items to the inventory.


b) Search for an item by product code.
c) Display details of all items in a specific category.
d) Update stock levels after a purchase or sale.

1. Develop a program for bubble sort and implement it in a virtual lab. CO2
[https://ds1-iiith.vlabs.ac.in/List%20of%20experiments.html]
2. Develop a program to perform searching: CO2
a) Develop a program to perform searching by applying Linear Search
technique.
b) Develop a program to perform searching by applying Binary Search
technique.
3. Build a program to perform sorting: CO2
c) Build a program to perform sorting by applying Selection Sort
d) Build a program to perform sorting by applying Quick Sort
4. Develop a program to implement stack and Queue: CO1
a) Develop a program to perform push operation in a stack.
b) Develop a program to perform pop operation in a stack.
c) Develop a program to perform insertion operation in a Queue.
d) Develop a program to perform deletion operation in a Queue.

5. Develop a program to implement linked list: CO3


a) Develop a program to create node in a linked list.
b) Develop a program to insert a node in a linked list.
c) Develop a program to traverse nodes of a linked list.
d) Develop a program to delete node in a linked list.

6. Develop a program to implement binary tree: CO3


a) Develop a program to insert node in a binary tree.

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

b) Develop a program to traverse nodes of a binary tree.


c) Develop a program to display node of a binary tree.
d) Develop a program to delete a node of a binary tree.

7. Build Program to implement DFS & BFS: CO4


a) Build Program to implement Depth First Search (DFS).
b) Build Program to implement Breadth First Search (BFS).
8. Develop a program to implement a Hash table: CO4
a) Build a program to insert an element in a hash table.
b) Build a program to display elements of a hash table.
c) Build a program to Search an element of a hash table.

d) Build a program to delete an element of a hash table.


Post Mini Project --
Lab:

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

S. B. JAIN INSTITUTE OF TECHNOLOGY,


MANAGEMENT & RESEARCH, NAGPUR.

Practical No. 0
(Pre Lab)
Aim: Develop a program to manage inventory of items in a store. Store
information-Product Name, Product Code, Category and Unit Price using
structure. Create a dynamic array of structure for various inventory items
and implement functions using pointers to:
a) Add new items to the inventory.
b) Search for an item by product code.
c) Display details of all items in a specific category.
d) Update stock levels after a purchase or sale.

Name of Student:

Roll No.:

Semester/Year:

Academic Session:

Date of Performance:

Date of Submission:

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)
AIM: Develop a program to manage inventory of items in a store. Store information-Product
Name, Product Code, Category and Unit Price using structure. Create a dynamic array of
structure for various inventory items and implement functions using pointers to:

a) Add new items to the inventory.


b) Search for an item by product code.
c) Display details of all items in a specific category.
d) Update stock levels after a purchase or sale.

OBJECTIVE/EXPECTED LEARNING OUTCOME:

• To make the student able to understand concept of DMA.


• To make the student able to understand concept of pointers and structure.
• To make students able to solve complex problems using DMA, Structure & Pointer.

Hardware and Software Requirement:


Hardware Requirement:
• Processor : Dual Core
• RAM : 1GB
• Hard Disk Drive : > 80 GB

Software Requirement:
• Operating System – Windows 2007
• IDE – Dev C++
• Online Platform: www.onlineGDB.com

THEORY:
DMA:
C dynamic memory allocation refers to performing manual memory management for
dynamic memory allocation in the C programming language via a group of functions in the C
standard library, namely malloc, realloc, calloc and free.

Since C is a structured language, it has some fixed rules for programming. One of them
includes changing the size of an array. An array is a collection of items stored at contiguous
memory locations.

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

As it can be seen that the length (size) of the array above made is 9. But what if there is a
requirement to change this length (size). For Example,

• If there is a situation where only 5 elements are needed to be entered in this array. In
this case, the remaining 4 indices are just wasting memory in this array. So there is a
requirement to lessen the length (size) of the array from 9 to
• Take another situation. In this, there is an array of 9 elements with all 9 indices
filled. But there is a need to enter 3 more elements in this array. In this case, 3
indices more are required. So the length (size) of the array needs to be changed
from 9 to 12.
This procedure is referred to as Dynamic Memory Allocation in C.

Therefore, C Dynamic Memory Allocation can be defined as a procedure in which the size
of a data structure (like Array) is changed during the runtime.
C provides some functions to achieve these tasks. There are 4 library functions provided by
C defined under <stdlib.h> header file to facilitate dynamic memory allocation in C
programming. They are:
1. malloc()

2. calloc()

3. free()

4. realloc()

Pointers:

The pointers in C language refer to the variables that hold the addresses of different
variables of similar data types. We use pointers to access the memory of the said variable
and then manipulate their addresses in a program.The pointers perform the function of
storing the addresses of other variables in the program. These variables could be of any
type- char, int, function, array, or other pointers. The pointer sizes depend on their

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)
architecture.

Structure:

The structure in C is a user-defined data type that can be used to group items of possibly
different types into a single type. The struct keyword is used to define the structure in the
C programming language. The items in the structure are called its member and they can
be of any valid data type.

• Structure Declaration
In structure declaration, we specify its member variables along with their datatype. We can
use the struct keyword to declare the structure in C using the following syntax:

Syntax
struct structure_name {
data_type member_name1;
data_type member_name1;
....
};
• Structure Definition
To use structure in our program, we have to define its instance. We can do that by creating
variables of the structure type. We can define structure variables using two methods:

1. Structure Variable Declaration with Structure Template


struct structure_name {
data_type member_name1;
data_type member_name1;
....
....
}variable1, varaible2, ...;

2. Structure Variable Declaration after Structure Template


// structure declared beforehand

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)
struct structure_name variable1, variable2, .......;

• Access Structure Members


We can access structure members by using the ( . ) dot operator.

Syntax
structure_name.member1;
strcuture_name.member2;
• Initialize Structure Members
We can initialize structure members in 3 ways which are as follows:
1. Using Assignment Operator.
2. Using Initializer List.
3. Using Designated Initializer List.

1. Initialization using Assignment Operator

struct structure_name str;


str.member1 = value1;
str.member2 = value2;
str.member3 = value3;
.

2. Initialization using Initializer List

struct structure_name str = { value1, value2, value3 };

In this type of initialization, the values are assigned in sequential order as they are declared in
the structure template.

3. Initialization using Designated Initializer List

Designated Initialization allows structure members to be initialized in any order.

struct structure_name str = { .member1 = value1, .member2 = value2, .member3 = value3 };

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)
ALGORITHM:

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

FLOWCHART:

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

CODE:

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

INPUT & OUTPUT (With Different Test Cases):

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

CONCLUSION:

DISCUSSION AND VIVA VOCE:

1. What is DMA ?
2. What is Pointer ?
3. What Structure ?
4. What is Array?
5. Explain types of DMA in Brief ?

REFERENCE:
1. Data Structures and Algorithms Concepts, Techniques and Applications, G A
Vijayalakshmi Pai, Mc-Graw Hill Education (India) Ltd. 2008.
2. Data Structures Using C, E Balgurusamy, Mc-Graw Hill Education (India) Ltd.

3. Data Structures Through C, Yashwant Kanetkar, BPB Publications.

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

S. B. JAIN INSTITUTE OF TECHNOLOGY,


MANAGEMENT & RESEARCH, NAGPUR.

Practical No. 1
Aim: Develop a program for bubble sort and implement it in a virtual
lab. [https://ds1-iiith.vlabs.ac.in/List%20of%20experiments.html]

Name of Student:
Roll No.:
Semester/Year:
Academic Session:
Date of Performance:
Date of Submission:

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

AIM: Develop a program for bubble sort and implement it in a virtual lab.
[https://ds1-iiith.vlabs.ac.in/List%20of%20experiments.html]

OBJECTIVE/EXPECTED LEARNING OUTCOME:


• To be able to understand sorting.
• To be able to implement bubble sorting.
• To be able to analyse various sorting techniques.

Hardware and Software Requirement:


Hardware Requirement:
• Processor : Dual Core
• RAM : 1GB
• Hard Disk Drive : > 80 GB

Software Requirement:
• Operating System – Windows 2007
• IDE – Dev C++
• Online Platform: www.onlineGDB.com

THEORY:
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent
elements if they are in the wrong order. This algorithm is not suitable for large data sets as its
average and worst-case time complexity is quite high.In Bubble Sort algorithm, traverse from
left and compare adjacent elements and the higher one is placed at right side. In this way, the
largest element is moved to the rightmost end at first. This process is then continued to find
the second largest and place it and so on until the data is sorted.

How does Bubble Sort Work?


Let us understand the working of bubble sort with the help of the following illustration:
Input: arr[] = {6, 0, 3, 5}

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

First Pass:
The largest element is placed in its correct position, i.e., the end of the array.

Second Pass:
Place the second largest element at correct position

Third Pass:
Place the remaining two elements at their correct positions.

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

Total no. of passes: n-1


Total no. of comparisons: n*(n-1)/2

ALGORITHM:

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

FLOWCHART:

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

CODE:

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

INPUT & OUTPUT (With Different Test Cases):

CONCLUSION:

DISCUSSION AND VIVA VOCE:


Q.1) Which asymptotic notation is better for time complexity analysis?
Q.2) What is the time complexity of binary search?
Q. 3) Which asymptotic notation provides upper as well as lower bound for function ?
Q.4) How many asymptotic notations are available? What are they?
Q. 5) how to calculate time complexity of merge sort?

REFERENCE:
1. Data Structures and Algorithms Concepts, Techniques and Applications, G A
Vijayalakshmi Pai, Mc-Graw Hill Education (India) Ltd. 2008.
2. Data Structures Using C, E Balgurusamy, Mc-Graw Hill Education (India) Ltd.

3. Data Structures Through C, Yashwant Kanetkar, BPB Publications.

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

S. B. JAIN INSTITUTE OF TECHNOLOGY,


MANAGEMENT & RESEARCH, NAGPUR.

Practical No. 2
Aim: Develop a program to perform searching:
a) Develop a program to perform searching by applying Linear
Search technique.
b) Develop a program to perform searching by applying Binary
Search technique.

Name of Student:
Roll No.:
Semester/Year:
Academic Session:
Date of Performance:
Date of Submission:

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

AIM: Develop a program to perform searching:


a) Develop a program to perform searching by applying Linear Search technique.
b) Develop a program to perform searching by applying Binary Search technique.

OBJECTIVE/EXPECTED LEARNING OUTCOME:


• To be able to understand the concept of Searching.
• To be able to implement Linear Search.
• To be able to implement Binary Search.

Hardware and Software Requirement:


Hardware Requirement:
• Processor : Dual Core
• RAM : 1GB
• Hard Disk Drive : > 80 GB

Software Requirement:
• Operating System – Windows 2007
• IDE – Dev C++
• Online Platform: www.onlineGDB.com

THEORY:

What is a linear search?

A linear search is also known as a sequential search that simply scans each element at a time.
Suppose we want to search an element in an array or list; we simply calculate its length and do
not jump at any item.
Let's consider a simple example.
Suppose we have an array of 10 elements as shown in the below figure:

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

The above figure shows an array of character type having 10 values. If we want to search 'E',
then the searching begins from the 0th element and scans each element until the element, i.e.,
'E' is not found. We cannot directly jump from the 0th element to the 4th element, i.e., each
element is scanned one by one till the element is not found.

Complexity of Linear search:

As linear search scans each element one by one until the element is not found. If the number
of elements increases, the number of elements to be scanned is also increased. We can say that
the time taken to search the elements is proportional to the number of elements. Therefore,
the worst-case complexity is O(n)

What is a Binary search?

A binary search is a search in which the middle element is calculated to check whether it is
smaller or larger than the element which is to be searched. The main advantage of using binary
search is that it does not scan each element in the list. Instead of scanning each element, it
performs the searching to the half of the list. So, the binary search takes less time to search an
element as compared to a linear search. The one pre-requisite of binary search is that an array
should be in sorted order, whereas the linear search works on both sorted and unsorted array.
The binary search algorithm is based on the divide and conquer technique, which means that it
will divide the array recursively.
There are three cases used in the binary search:
Case 1: data<a[mid] then left = mid+1.
Case 2: data>a[mid] then right=mid-1
Case 3: data = a[mid] // element is found
In the above case, 'a' is the name of the array, mid is the index of the element calculated
recursively, data is the element that is to be searched, left denotes the left element of the array
and right denotes the element that occur on the right side of the array.
Let's understand the working of binary search through an example.

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

Suppose we have an array of 10 size which is indexed from 0 to 9 as shown in the below figure:
We want to search for 70 element from the above array.
Step 1: First, we calculate the middle element of an array. We consider two variables, i.e., left
and right. Initially, left =0 and right=9 as shown in the below figure:

The middle element value can be calculated as:

Therefore, mid = 4 and a[mid] = 50. The element to be searched is 70, so a[mid] is not equal
to data. The case 2 is satisfied, i.e., data>a[mid].

Step 2: As data>a[mid], so the value of left is incremented by mid+1, i.e., left=mid+1. The
value of mid is 4, so the value of left becomes 5. Now, we have got a subarray as shown in the
below figure:

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

Now again, the mid-value is calculated by using the above formula, and the value of mid
becomes 7. Now, the mid can be represented as:

In the above figure, we can observe that a[mid]>data, so again, the value of mid will be
calculated in the next step.
Step 3: As a[mid]>data, the value of right is decremented by mid-1. The value of mid is 7, so
the value of right becomes 6. The array can be represented as:

The value of mid will be calculated again. The values of left and right are 5 and 6, respectively.
Therefore, the value of mid is 5. Now the mid can be represented in an array as shown below:

In the above figure, we can observe that a[mid]<data.

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

Step 4: As a[mid]<data, the left value is incremented by mid+1. The value of mid is 5, so the
value of left becomes 6.
Now the value of mid is calculated again by using the formula which we have already
discussed. The values of left and right are 6 and 6 respectively, so the value of mid becomes 6
as shown in the below figure:

We can observe in the above figure that a[mid]=data. Therefore, the search is completed, and
the element is found successfully.

a) Develop a program to perform searching by applying Linear Search technique.

ALGORITHM:

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

FLOWCHART:

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

CODE:

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

INPUT & OUTPUT (With Different Test Cases):

b) Develop a program to perform searching by applying Binary Search technique.

ALGORITHM:

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

FLOWCHART:

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

CODE:

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

INPUT & OUTPUT (With Different Test Cases):

CONCLUSION:

DISCUSSION AND VIVA VOCE:


Q.1) What is Searching?
Q. 2) What are various types of searching?
Q. 3) Can we perform binary search on unsorted array?
Q. 4) How can you perform searching in queue?
Q. 5) How to perform searching in BST?
Q. 6) How to search an element in stack memory?

REFERENCE:
● Data Structures and Algorithms Concepts, Techniques and Applications, G A
Vijayalakshmi Pai, Mc-Graw Hill Education (India) Ltd. 2008.
● Data Structures Using C, E Balgurusamy, Mc-Graw Hill Education (India) Ltd.

● Data Structures Through C, Yashwant Kanetkar, BPB Publications.

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

S. B. JAIN INSTITUTE OF TECHNOLOGY,


MANAGEMENT & RESEARCH, NAGPUR.

Practical No. 3
Aim: Build a program to perform sorting:
a) Build a program to perform sorting by applying Selection Sort
b) Build a program to perform sorting by applying Quick Sort

Name of Student:
Roll No.:
Semester/Year:
Academic Session:
Date of Performance:
Date of Submission:

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

AIM: Build a program to perform sorting:


a) Build a program to perform sorting by applying Selection Sort
b) Build a program to perform sorting by applying Quick Sort

OBJECTIVE/EXPECTED LEARNING OUTCOME:


● To be able to understand the concept of sorting.
● To be will be able to understand the various sorting techniques.
● To be able to implement Selection sort and Quick sort.

Hardware and Software Requirement:


Hardware Requirement:
● Processor : Dual Core
● RAM : 1GB
● Hard Disk Drive : > 80 GB

Software Requirement:
● Operating System – Windows 2007
● IDE – Dev C++
● Online Platform: www.onlineGDB.com

THEORY:
A sorting algorithm is used to arrange elements of an array/list in a specific order. For example,

Here, we are sorting the array in ascending order.


There are various sorting algorithms that can be used to complete this operation. And, we can
use any algorithm based on the requirement.

Different Sorting Algorithms:

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

● Bubble Sort
● Selection Sort
● Insertion Sort
● Merge Sort
● Quicksort
● Counting Sort
● Radix Sort
● Bucket Sort
● Heap Sort
● Shell Sort

Selection Sort:
Selection sort is a simple and efficient sorting algorithm that works by repeatedly selecting
the smallest (or largest) element from the unsorted portion of the list and moving it to the
sorted portion of the list. The algorithm repeatedly selects the smallest (or largest) element
from the unsorted portion of the list and swaps it with the first element of the unsorted part.
This process is repeated for the remaining unsorted portion until the entire list is sorted.

How does Selection Sort Algorithm work?


Lets consider the following array as an example: arr[] = {64, 25, 12, 22, 11}

First pass:
For the first position in the sorted array, the whole array is traversed from index 0 to 4
sequentially. The first position where 64 is stored presently, after traversing whole array it is
clear that 11 is the lowest value.
Thus, replace 64 with 11. After one iteration 11, which happens to be the least value in the
array, tends to appear in the first position of the sorted list.

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

Second Pass:
For the second position, where 25 is present, again traverse the rest of the array in a
sequential manner.
After traversing, we found that 12 is the second lowest value in the array and it should appear
at the second place in the array, thus swap these values.

Third Pass:
Now, for third place, where 25 is present again traverse the rest of the array and find the third
least value present in the array.
While traversing, 22 came out to be the third least value and it should appear at the third
place in the array, thus swap 22 with element present at third position.

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

Fourth pass:
Similarly, for fourth position traverse the rest of the array and find the fourth least element in
the array. As 25 is the 4th lowest value hence, it will place at the fourth position.

Fifth Pass:
At last the largest value present in the array automatically get placed at the last position in the
array. The resulted array is the sorted array.

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

Quick Sort:
Sorting is a way of arranging items in a systematic manner. Quicksort is the widely used sorting
algorithm that makes n log n comparisons in average case for sorting an array of n elements.
It is a faster and highly efficient sorting algorithm. This algorithm follows the divide and
conquer approach. Divide and conquer is a technique of breaking down the algorithms into
subproblems, then solving the subproblems, and combining the results back together to solve
the original problem.
Divide: In Divide, first pick a pivot element. After that, partition or rearrange the array into
two sub-arrays such that each element in the left sub-array is less than or equal to the pivot
element and each element in the right sub-array is larger than the pivot element.
Conquer: Recursively, sort two subarrays with Quicksort.
Combine: Combine the already sorted array.
Quicksort picks an element as pivot, and then it partitions the given array around the picked
pivot element. In quick sort, a large array is divided into two arrays in which one holds values
that are smaller than the specified value (Pivot), and another array holds the values that are
greater than the pivot.
After that, left and right sub-arrays are also partitioned using the same approach. It will
continue until the single element remains in the sub-array.

Choosing the pivot:


Picking a good pivot is necessary for the fast implementation of quicksort. However, it is
typical to determine a good pivot. Some of the ways of choosing a pivot are as follows -
o Pivot can be random, i.e. select the random pivot from the given array.
o Pivot can either be the rightmost element of the leftmost element of the given array.
o Select median as the pivot element.

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

Working of Quick Sort Algorithm:


Now, let's see the working of the Quicksort Algorithm.

To understand the working of quick sort, let's take an unsorted array. It will make the concept
more clear and understandable.

Let the elements of array are -

In the given array, we consider the leftmost element as pivot. So, in this case, a[left] = 24,
a[right] = 27 and a[pivot] = 24.

Since, pivot is at left, so algorithm starts from right and move towards left.

Now, a[pivot] < a[right], so algorithm moves forward one position towards left, i.e. -

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

Now, a[left] = 24, a[right] = 19, and a[pivot] = 24.

Because, a[pivot] > a[right], so, algorithm will swap a[pivot] with a[right], and pivot moves to
right, as -

Now, a[left] = 19, a[right] = 24, and a[pivot] = 24. Since, pivot is at right, so algorithm starts
from left and moves to right.

As a[pivot] > a[left], so algorithm moves one position to right as -

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

Now, a[left] = 9, a[right] = 24, and a[pivot] = 24. As a[pivot] > a[left], so algorithm moves one
position to right as -

Now, a[left] = 29, a[right] = 24, and a[pivot] = 24. As a[pivot] < a[left], so, swap a[pivot] and
a[left], now pivot is at left, i.e. -

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

Since, pivot is at left, so algorithm starts from right, and move to left. Now, a[left] = 24, a[right]
= 29, and a[pivot] = 24. As a[pivot] < a[right], so algorithm moves one position to left, as -

Now, a[pivot] = 24, a[left] = 24, and a[right] = 14. As a[pivot] > a[right], so, swap a[pivot] and
a[right], now pivot is at right, i.e. -

Now, a[pivot] = 24, a[left] = 14, and a[right] = 24. Pivot is at right, so the algorithm starts from
left and move to right.

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

Now, a[pivot] = 24, a[left] = 24, and a[right] = 24. So, pivot, left and right are pointing the
same element. It represents the termination of procedure.

Element 24, which is the pivot element is placed at its exact position.

Elements that are right side of element 24 are greater than it, and the elements that are left side
of element 24 are smaller than it.

Now, in a similar manner, quick sort algorithm is separately applied to the left and right sub-
arrays. After sorting gets done, the array will be -

a) Build a program to perform sorting by applying Selection Sort

ALGORITHM:

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

FLOWCHART:

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

CODE:

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

INPUT & OUTPUT (With Different Test Cases):

b) Build a program to perform sorting by applying Quick Sort

ALGORITHM:

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

FLOWCHART:

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

CODE:

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

INPUT & OUTPUT (With Different Test Cases):

CONCLUSION:

DISCUSSION AND VIVA VOCE:


Q.1) What is sort order?
Q.2) What is stable and unstable sorting algo?
Q.3) How to find efficiency of a sorting algo?
Q.4) What are sorting algorithms available?
Q.5) Explain heap sort and bucket sort algorithm.

REFERENCE:
● Data Structures and Algorithms Concepts, Techniques and Applications, G A
Vijayalakshmi Pai, Mc-Graw Hill Education (India) Ltd. 2008.
● Data Structures Using C, E Balgurusamy, Mc-Graw Hill Education (India) Ltd.

● Data Structures Through C, Yashwant Kanetkar, BPB Publications.

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

S. B. JAIN INSTITUTE OF TECHNOLOGY,


MANAGEMENT & RESEARCH, NAGPUR.

Practical No. 4
Aim: Develop a program to implement stack and Queue:
a) Develop a program to perform push operation in a stack.
b) Develop a program to perform pop operation in a stack.
c) Develop a program to perform insertion operation in a Queue.
d) Develop a program to perform deletion operation in a Queue.

Name of Student:
Roll No.:
Semester/Year:
Academic Session:
Date of Performance:
Date of Submission:

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

AIM: Develop a program to implement stack and Queue:


a) Develop a program to perform push operation in a stack.
b) Develop a program to perform pop operation in a stack.
c) Develop a program to perform insertion operation in a Queue.
d) Develop a program to perform deletion operation in a Queue.

OBJECTIVE/EXPECTED LEARNING OUTCOME:

● To be able to understand the concept of Stack.


● To be will be able to understand the various types of queues.
● To be able to implement stack and queue.

Hardware and Software Requirement:


Hardware Requirement:
● Processor : Dual Core
● RAM : 1GB
● Hard Disk Drive : > 80 GB

Software Requirement:
● Operating System – Windows 2007
● IDE – Dev C++
● Online Platform: www.onlineGDB.com

THEORY:

What is a Stack?
A Stack is a linear data structure that follows the LIFO (Last-In-First-Out) principle. Stack
has one end, whereas the Queue has two ends (front and rear). It contains only one pointer top
pointer pointing to the topmost element of the stack. Whenever an element is added in the
stack, it is added on the top of the stack, and the element can be deleted only from the stack. In
other words, a stack can be defined as a container in which insertion and deletion can be
done from the one end known as the top of the stack.

Some key points related to stack:

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

o It is called as stack because it behaves like a real-world stack, piles of books, etc.
o A Stack is an abstract data type with a pre-defined capacity, which means that it can
store the elements of a limited size.
o It is a data structure that follows some order to insert and delete the elements, and that
order can be LIFO or FILO.

Working of Stack:
Stack works on the LIFO pattern. As we can observe in the below figure there are five memory
blocks in the stack; therefore, the size of the stack is 5.
Suppose we want to store the elements in a stack and let's assume that stack is empty. We have
taken the stack of size 5 as shown below in which we are pushing the elements one by one until
the stack becomes full.

Since our stack is full as the size of the stack is 5. In the above cases, we can observe that it
goes from the top to the bottom when we were entering the new element in the stack. The stack
gets filled up from the bottom to the top.
When we perform the delete operation on the stack, there is only one way for entry and exit as
the other end is closed. It follows the LIFO pattern, which means that the value entered first
will be removed last. In the above case, the value 5 is entered first, so it will be removed only
after the deletion of all the other elements.

Standard Stack Operations:


The following are some common operations implemented on the stack:
o push(): When we insert an element in a stack then the operation is known as a push. If
the stack is full then the overflow condition occurs.

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

o pop(): When we delete an element from the stack, the operation is known as a pop. If
the stack is empty means that no element exists in the stack, this state is known as an
underflow state.
o isEmpty(): It determines whether the stack is empty or not.
o isFull(): It determines whether the stack is full or not.'
o peek(): It returns the element at the given position.
o count(): It returns the total number of elements available in a stack.
o change(): It changes the element at the given position.
o display(): It prints all the elements available in the stack.

PUSH operation:
The steps involved in the PUSH operation is given below:
o Before inserting an element in a stack, we check whether the stack is full.
o If we try to insert the element in a stack, and the stack is full, then
the overflow condition occurs.
o When we initialize a stack, we set the value of top as -1 to check that the stack is empty.
o When the new element is pushed in a stack, first, the value of the top gets incremented,
i.e., top=top+1, and the element will be placed at the new position of the top.
o The elements will be inserted until we reach the max size of the stack.

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

POP operation:

The steps involved in the POP operation is given below:


o Before deleting the element from the stack, we check whether the stack is empty.
o If we try to delete the element from the empty stack, then the underflow condition
occurs.
o If the stack is not empty, we first access the element which is pointed by the top
o Once the pop operation is performed, the top is decremented by 1, i.e., top=top-1.

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

Applications of Stack:

The following are the applications of the stack:


o Balancing of symbols: Stack is used for balancing a symbol. For example, we have the
following program:

int main()
{
cout<<"Hello";
cout<<"javaTpoint";
}
As we know, each program has an opening and closing braces; when the opening braces come,
we push the braces in a stack, and when the closing braces appear, we pop the opening braces
from the stack. Therefore, the net value comes out to be zero. If any symbol is left in the stack,
it means that some syntax occurs in a program.
o String reversal: Stack is also used for reversing a string. For example, we want to reverse
a "javaTpoint" string, so we can achieve this with the help of a stack.
First, we push all the characters of the string in a stack until we reach the null character.

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

After pushing all the characters, we start taking out the character one by one until we reach
the bottom of the stack.
o UNDO/REDO: It can also be used for performing UNDO/REDO operations. For example,
we have an editor in which we write 'a', then 'b', and then 'c'; therefore, the text written in
an editor is abc. So, there are three states, a, ab, and abc, which are stored in a stack. There
would be two stacks in which one stack shows UNDO state, and the other shows REDO
state.
If we want to perform UNDO operation, and want to achieve 'ab' state, then we implement
pop operation.
o Recursion: The recursion means that the function is calling itself again. To maintain the
previous states, the compiler creates a system stack in which all the previous records of the
function are maintained.
o DFS(Depth First Search): This search is implemented on a Graph, and Graph uses the
stack data structure.
o Backtracking: Suppose we have to create a path to solve a maze problem. If we are moving
in a particular path, and we realize that we come on the wrong way. In order to come at the
beginning of the path to create a new path, we have to use the stack data structure.
o Expression conversion: Stack can also be used for expression conversion. This is one of
the most important applications of stack. The list of the expression conversion is given
below:
o Infix to prefix
o Infix to postfix
o Prefix to infix
o Prefix to postfix
Postfix to infix
o Memory management: The stack manages the memory. The memory is assigned in the
contiguous memory blocks. The memory is known as stack memory as all the variables are
assigned in a function call stack memory. The memory size assigned to the program is
known to the compiler. When the function is created, all its variables are assigned in the
stack memory. When the function completed its execution, all the variables assigned in the
stack are released.

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

Queue:
1. A queue can be defined as an ordered list which enables insert operations to be performed at
one end called REAR and delete operations to be performed at another end called FRONT.
2. Queue is referred to be as First In First Out list.
3. For example, people waiting in line for a rail ticket form a queue.

Applications of Queue:
Due to the fact that queue performs actions on first in first out basis which is quite fair for the
ordering of actions. There are various applications of queues discussed as below.
1. Queues are widely used as waiting lists for a single shared resource like printer, disk,
CPU.
2. Queues are used in asynchronous transfer of data (where data is not being transferred
at the same rate between two processes) for eg. pipes, file IO, sockets.
3. Queues are used as buffers in most of the applications like MP3 media player, CD
player, etc.
4. Queue are used to maintain the play list in media players in order to add and remove
the songs from the play-list.
5. Queues are used in operating systems for handling interrupts.

Basic Operations:
Queue operations may involve initializing or defining the queue, utilizing it, and then
completely erasing it from the memory. Here we shall try to understand the basic operations
associated with queues −
• enqueue() − add (store) an item to the queue.

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

• dequeue() − remove (access) an item from the queue.


• Few more functions are required to make the above-mentioned queue operation
efficient. These are −
• peek() − Gets the element at the front of the queue without removing it.
• isfull() − Checks if the queue is full.
• isempty() − Checks if the queue is empty.
In queue, we always dequeue (or access) data, pointed by front pointer and while enqueuing
(or storing) data in the queue we take help of rear pointer.

a) & b)Develop a program to perform push and pop operation in a stack.

ALGORITHM:

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

FLOWCHART:

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

CODE:

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

INPUT & OUTPUT (With Different Test Cases):

c) & d) Develop a program to perform insertion and deletion operation in a Queue.

ALGORITHM:

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

FLOWCHART:

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

CODE:

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

INPUT & OUTPUT (With Different Test Cases):

CONCLUSION:

DISCUSSION AND VIVA VOCE:


Q.1) What is stack? How does it work?
Q.2) What is queue? Can we implement queue using linked list?
Q.3) what time complexity for push operation in stack? Can we implement linked list as stack?
Q.4) What is space complexity for insert operation in a circular queue?
Q.5) Explain various operation of stack and queue.

REFERENCE:
● Data Structures and Algorithms Concepts, Techniques and Applications, G A
Vijayalakshmi Pai, Mc-Graw Hill Education (India) Ltd. 2008.
● Data Structures Using C, E Balgurusamy, Mc-Graw Hill Education (India) Ltd.

● Data Structures Through C, Yashwant Kanetkar, BPB Publications.

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

S. B. JAIN INSTITUTE OF TECHNOLOGY,


MANAGEMENT & RESEARCH, NAGPUR.

Practical No. 5
Aim: Develop a program to implement linked list:
a) Develop a program to create node in a linked list.
b) Develop a program to insert a node in a linked list.
c) Develop a program to traverse nodes of a linked list.
d) Develop a program to delete node in a linked list.

Name of Student:
Roll No.:
Semester/Year:
Academic Session:
Date of Performance:
Date of Submission:

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

AIM: Develop a program to implement linked list:


a) Develop a program to create node in a linked list.
b) Develop a program to insert a node in a linked list.
c) Develop a program to traverse nodes of a linked list.
d) Develop a program to delete node in a linked list.

OBJECTIVE/EXPECTED LEARNING OUTCOME:

● To be able to understand the concept of linked list.


● To be will be able to understand the various types of linked list.
● To be able to implement various operation in various linked list.

Hardware and Software Requirement:


Hardware Requirement:
● Processor : Dual Core
● RAM : 1GB
● Hard Disk Drive : > 80 GB

Software Requirement:
● Operating System – Windows 2007
● IDE – Dev C++
● Online Platform: www.onlineGDB.com

THEORY:

Linked List:
o Linked List can be defined as collection of objects called nodes that are randomly
stored in the memory.
o A node contains two fields i.e. data stored at that particular address and the pointer
which contains the address of the next node in the memory.
o The last node of the list contains pointer to the null.

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

Uses of Linked List:


o The list is not required to be contiguously present in the memory. The node can reside
any where in the memory and linked together to make a list. This achieves optimized
utilization of space.
o list size is limited to the memory size and doesn't need to be declared in advance.
o Empty node can not be present in the linked list.
o We can store values of primitive types or objects in the singly linked list.

Why use linked list over array?


Till now, we were using array data structure to organize the group of elements that are to be
stored individually in the memory. However, Array has several advantages and disadvantages
which must be known in order to decide the data structure which will be used throughout the
program.
Array contains following limitations:
1. The size of array must be known in advance before using it in the program.
2. Increasing size of the array is a time taking process. It is almost impossible to expand
the size of the array at run time.
3. All the elements in the array need to be contiguously stored in the memory. Inserting
any element in the array needs shifting of all its predecessors.

Linked list is the data structure which can overcome all the limitations of an array. Using linked
list is useful because,
1. It allocates the memory dynamically. All the nodes of linked list are non-contiguously
stored in the memory and linked together with the help of pointers.

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

2. Sizing is no longer a problem since we do not need to define its size at the time of
declaration. List grows as per the program's demand and limited to the available
memory space.

Singly linked list or One way chain:


Singly linked list can be defined as the collection of ordered set of elements. The number of
elements may vary according to need of the program. A node in the singly linked list consist
of two parts: data part and link part. Data part of the node stores actual information that is to
be represented by the node while the link part of the node stores the address of its immediate
successor.

One way chain or singly linked list can be traversed only in one direction. In other words, we
can say that each node contains only next pointer, therefore we can not traverse the list in the
reverse direction.

Consider an example where the marks obtained by the student in three subjects are stored in a
linked list as shown in the figure.

In the above figure, the arrow represents the links. The data part of every node contains the
marks obtained by the student in the different subject. The last node in the list is identified by
the null pointer which is present in the address part of the last node. We can have as many
elements we require, in the data part of the list.

Operations on Singly Linked List:


There are various operations which can be performed on singly linked list. A list of all such
operations is given below.

Node Creation

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

struct node
{
int data;
struct node *next;
};
struct node *head, *ptr;
ptr = (struct node *)malloc(sizeof(struct node *));

Insertion

The insertion into a singly linked list can be performed at different positions. Based on the
position of the new node being inserted, the insertion is categorized into the following
categories.

Sr. Operation Description


No.

1 Insertion at It involves inserting any element at the front of the list. We


beginning just need to a few link adjustments to make the new node as
the head of the list.

2 Insertion at end of It involves insertion at the last of the linked list. The new
the list node can be inserted as the only node in the list or it can be
inserted as the last one. Different logics are implemented in
each scenario.

3 Insertion after It involves insertion after the specified node of the linked list.
specified node We need to skip the desired number of nodes in order to
reach the node after which the new node will be inserted. .

Deletion and Traversing

The Deletion of a node from a singly linked list can be performed at different positions. Based
on the position of the node being deleted, the operation is categorized into the following
categories.

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

So. Operation Description


No.

1 Deletion at It involves deletion of a node from the beginning of the list. This is
1 beginning the simplest operation among all. It just need a few adjustments in the
node pointers.

2 Deletion at the It involves deleting the last node of the list. The list can either be
2 end of the list empty or full. Different logic is implemented for the different
scenarios.

3 Deletion after It involves deleting the node after the specified node in the list. we
3 specified node need to skip the desired number of nodes to reach the node after which
the node will be deleted. This requires traversing through the list.

4 Traversing In traversing, we simply visit each node of the list at least once in
4 order to perform some specific operation on it, for example, printing
data part of each node present in the list.

5 Searching In searching, we match each element of the list with the given
5 element. If the element is found on any of the location then location
of that element is returned otherwise null is returned. .

Doubly linked list:


Doubly linked list is a complex type of linked list in which a node contains a pointer to the
previous as well as the next node in the sequence. Therefore, in a doubly linked list, a node
consists of three parts: node data, pointer to the next node in sequence (next pointer) , pointer
to the previous node (previous pointer). A sample node in a doubly linked list is shown in the
figure.

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

A doubly linked list containing three nodes having numbers from 1 to 3 in their data part, is
shown in the following image.

In C, structure of a node in doubly linked list can be given as :


struct node
{
struct node *prev;
int data;
struct node *next;
}
The prev part of the first node and the next part of the last node will always contain null
indicating end in each direction.
In a singly linked list, we could traverse only in one direction, because each node contains
address of the next node and it doesn't have any record of its previous nodes. However, doubly
linked list overcome this limitation of singly linked list. Due to the fact that, each node of the
list contains the address of its previous node, we can find all the details about the previous node
as well by using the previous address stored inside the previous part of each node.

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

Memory Representation of a doubly linked list:


Memory Representation of a doubly linked list is shown in the following image. Generally,
doubly linked list consumes more space for every node and therefore, causes more expansive
basic operations such as insertion and deletion. However, we can easily manipulate the
elements of the list since the list maintains pointers in both the directions (forward and
backward).
In the following image, the first element of the list that is i.e. 13 stored at address 1. The head
pointer points to the starting address 1. Since this is the first element being added to the list
therefore the prev of the list contains null. The next node of the list resides at address 4
therefore the first node contains 4 in its next pointer.
We can traverse the list in this way until we find any node containing null or -1 in its next part.

Operations on doubly linked list:


Node Creation:
struct node
{
struct node *prev;
int data;
struct node *next;

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

};
struct node *head;
All the remaining operations regarding doubly linked list are described in the following table.

Sr. Operation Description


No.

1 Insertion at beginning Adding the node into the linked list at beginning.

2 Insertion at end Adding the node into the linked list to the end.

3 Insertion after specified Adding the node into the linked list after the specified node.
node

4 Deletion at beginning Removing the node from beginning of the list

5 Deletion at the end Removing the node from end of the list.

6 Deletion of the node Removing the node which is present just after the node
having given data containing the given data.

7 Searching Comparing each node data with the item to be searched and
return the location of the item in the list if the item found
else return null.

8 Traversing Visiting each node of the list at least once in order to


perform some specific operation like searching, sorting,
display, etc.

a) & b) Develop a program to create and insert node in a linked list.

ALGORITHM:

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

FLOWCHART:

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

CODE:

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

INPUT & OUTPUT (With Different Test Cases):

c) & d) Develop a program to traverse and delete node in a linked list.

ALGORITHM:

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

FLOWCHART:

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

CODE:

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

INPUT & OUTPUT (With Different Test Cases):

CONCLUSION:

DISCUSSION AND VIVA VOCE:


Q.1) What is linked list?
Q.2) What are various types of linked list?
Q.3) Can we join two linked list together?
Q.4) What operations can be performed on doubly circular linked list?
Q.5) Can you implement priority queue using linked list?

REFERENCE:
● Data Structures and Algorithms Concepts, Techniques and Applications, G A
Vijayalakshmi Pai, Mc-Graw Hill Education (India) Ltd. 2008.
● Data Structures Using C, E Balgurusamy, Mc-Graw Hill Education (India) Ltd.

● Data Structures Through C, Yashwant Kanetkar, BPB Publications.

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

S. B. JAIN INSTITUTE OF TECHNOLOGY,


MANAGEMENT & RESEARCH, NAGPUR.

Practical No. 6
Aim: Develop a program to implement binary tree:
a) Develop a program to insert node in a binary tree.
b) Develop a program to traverse nodes of a binary tree.
c) Develop a program to display node of a binary tree.
d) Develop a program to delete a node of a binary tree.

Name of Student:
Roll No.:
Semester/Year:
Academic Session:
Date of Performance:
Date of Submission:

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

AIM: Develop a program to implement binary tree:


a) Develop a program to insert node in a binary tree.
b) Develop a program to traverse nodes of a binary tree.
c) Develop a program to display node of a binary tree.
d) Develop a program to delete a node of a binary tree.

OBJECTIVE/EXPECTED LEARNING OUTCOME:

● To be able to understand the concept of trees.


● To be will be able to understand the various types of trees.
● To be able to implement various operation in various trees.

Hardware and Software Requirement:


Hardware Requirement:
● Processor : Dual Core
● RAM : 1GB
● Hard Disk Drive : > 80 GB
Software Requirement:
● Operating System – Windows 2007
● IDE – Dev C++
● Online Platform: www.onlineGDB.com

THEORY:
A tree is also one of the data structures that represent hierarchical data. Suppose we want to
show the employees and their positions in the hierarchical form then it can be represented as
shown below:

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

The above tree shows the organization hierarchy of some company. In the above
structure, john is the CEO of the company, and John has two direct reports named
as Steve and Rohan. Steve has three direct reports named Lee, Bob, Ella where Steve is a
manager. Bob has two direct reports named Sal and Emma. Emma has two direct reports
named Tom and Raj. Tom has one direct report named Bill. This particular logical structure is
known as a Tree. Its structure is similar to the real tree, so it is named a Tree. In this structure,
the root is at the top, and its branches are moving in a downward direction. Therefore, we can
say that the Tree data structure is an efficient way of storing the data in a hierarchical way.

Let's understand some key points of the Tree data structure.


o A tree data structure is defined as a collection of objects or entities known as nodes that
are linked together to represent or simulate hierarchy.
o A tree data structure is a non-linear data structure because it does not store in a
sequential manner. It is a hierarchical structure as elements in a Tree are arranged in
multiple levels.
o In the Tree data structure, the topmost node is known as a root node. Each node contains
some data, and data can be of any type. In the above tree structure, the node contains
the name of the employee, so the type of data would be a string.
o Each node contains some data and the link or reference of other nodes that can be called
children.

Some basic terms used in Tree data structure:


Let's consider the tree structure, which is shown below:

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

In the above structure, each node is labeled with some number. Each arrow shown in the above
figure is known as a link between the two nodes.

o Root: The root node is the topmost node in the tree hierarchy. In other words, the root
node is the one that doesn't have any parent. In the above structure, node numbered 1
is the root node of the tree. If a node is directly linked to some other node, it would
be called a parent-child relationship.
o Child node: If the node is a descendant of any node, then the node is known as a child
node.
o Parent: If the node contains any sub-node, then that node is said to be the parent of that
sub-node.
o Sibling: The nodes that have the same parent are known as siblings.
o Leaf Node:- The node of the tree, which doesn't have any child node, is called a leaf
node. A leaf node is the bottom-most node of the tree. There can be any number of leaf
nodes present in a general tree. Leaf nodes can also be called external nodes.
o Internal nodes: A node has atleast one child node known as an internal
o Ancestor node:- An ancestor of a node is any predecessor node on a path from the root
to that node. The root node doesn't have any ancestors. In the tree shown in the above
image, nodes 1, 2, and 5 are the ancestors of node 10.
o Descendant: The immediate successor of the given node is known as a descendant of
a node. In the above figure, 10 is the descendant of node 5.

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

Implementation of Tree:

The tree data structure can be created by creating the nodes dynamically with the help of the
pointers. The tree in the memory can be represented as shown below:

The above figure shows the representation of the tree data structure in the memory. In the above
structure, the node contains three fields. The second field stores the data; the first field stores
the address of the left child, and the third field stores the address of the right child.
In programming, the structure of a node can be defined as:
struct node
{
int data;
struct node *left;
struct node *right;
}
The above structure can only be defined for the binary trees because the binary tree can have
utmost two children, and generic trees can have more than two children. The structure of the
node for generic trees would be different as compared to the binary tree.

Applications of trees:

The following are the applications of trees:


o Storing naturally hierarchical data: Trees are used to store the data in the hierarchical
structure. For example, the file system. The file system stored on the disc drive, the file

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

and folder are in the form of the naturally hierarchical data and stored in the form of
trees.
o Organize data: It is used to organize data for efficient insertion, deletion and
searching. For example, a binary tree has a logN time for searching an element.
o Trie: It is a special kind of tree that is used to store the dictionary. It is a fast and
efficient way for dynamic spell checking.
o Heap: It is also a tree data structure implemented using arrays. It is used to implement
priority queues.
o B-Tree and B+Tree: B-Tree and B+Tree are the tree data structures used to implement
indexing in databases.
o Routing table: The tree data structure is also used to store the data in routing tables in
the routers.

Types of Tree data structure:

The following are the types of a tree data structure:


o General tree: The general tree is one of the types of tree data structure. In the general
tree, a node can have either 0 or maximum n number of nodes. There is no restriction
imposed on the degree of the node (the number of nodes that a node can contain). The
topmost node in a general tree is known as a root node. The children of the parent node
are known as subtrees.

There can be n number of subtrees in a general tree. In the general tree, the subtrees are

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

unordered as the nodes in the subtree cannot be ordered.


Every non-empty tree has a downward edge, and these edges are connected to the nodes
known as child nodes. The root node is labeled with level 0. The nodes that have the
same parent are known as siblings.

o Binary tree: Here, binary name itself suggests two numbers, i.e., 0 and 1. In a binary
tree, each node in a tree can have utmost two child nodes. Here, utmost means
whether the node has 0 nodes, 1 node or 2 nodes.

o Binary Search tree: Binary search tree is a non-linear data structure in which one node
is connected to n number of nodes. It is a node-based data structure. A node can be
represented in a binary search tree with three fields, i.e., data part, left-child, and right-
child. A node can be connected to the utmost two child nodes in a binary search tree,
so the node contains two pointers (left child and right child pointer).
Every node in the left subtree must contain a value less than the value of the root node,
and the value of each node in the right subtree must be bigger than the value of the root
node.

A node can be created with the help of a user-defined data type known as struct, as
shown below:
struct node
{
int data;
struct node *left;
struct node *right;
}

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

The above is the node structure with three fields: data field, the second field is the left
pointer of the node type, and the third field is the right pointer of the node type.

o AVL tree

It is one of the types of the binary tree, or we can say that it is a variant of the binary
search tree. AVL tree satisfies the property of the binary tree as well as of the binary
search tree. It is a self-balancing binary search tree that was invented by Adelson
Velsky Lindas. Here, self-balancing means that balancing the heights of left subtree
and right subtree. This balancing is measured in terms of the balancing factor.
We can consider a tree as an AVL tree if the tree obeys the binary search tree as well
as a balancing factor. The balancing factor can be defined as the difference between
the height of the left subtree and the height of the right subtree. The balancing
factor's value must be either 0, -1, or 1; therefore, each node in the AVL tree should
have the value of the balancing factor either as 0, -1, or 1.
o Red-Black Tree

The red-Black tree is the binary search tree. The prerequisite of the Red-Black tree is that
we should know about the binary search tree. In a binary search tree, the value of the left-
subtree should be less than the value of that node, and the value of the right-subtree should
be greater than the value of that node. As we know that the time complexity of binary
search in the average case is log2n, the best case is O(1), and the worst case is O(n).
When any operation is performed on the tree, we want our tree to be balanced so that all
the operations like searching, insertion, deletion, etc., take less time, and all these
operations will have the time complexity of log2n.
The red-black tree is a self-balancing binary search tree. AVL tree is also a height
balancing binary search tree then why do we require a Red-Black tree. In the AVL tree,
we do not know how many rotations would be required to balance the tree, but in the Red-
black tree, a maximum of 2 rotations are required to balance the tree. It contains one extra
bit that represents either the red or black color of a node to ensure the balancing of the
tree.
o Splay tree

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

The splay tree data structure is also binary search tree in which recently accessed element
is placed at the root position of tree by performing some rotation operations.
Here, splaying means the recently accessed node. It is a self-balancing binary search tree
having no explicit balance condition like AVL tree.
It might be a possibility that height of the splay tree is not balanced, i.e., height of both
left and right subtrees may differ, but the operations in splay tree takes order of logN time
where n is the number of nodes.
Splay tree is a balanced tree but it cannot be considered as a height balanced tree because
after each operation, rotation is performed which leads to a balanced tree.
o B-tree

B-tree is a balanced m-way tree where m defines the order of the tree. Till now, we read
that the node contains only one key but b-tree can have more than one key, and more than
2 children. It always maintains the sorted data. In binary tree, it is possible that leaf nodes
can be at different levels, but in b-tree, all the leaf nodes must be at the same level.
If order is m then node has the following properties:
o Each node in a b-tree can have maximum m children
o For minimum children, a leaf node has 0 children, root node has minimum 2 children
and internal node has minimum ceiling of m/2 children. For example, the value of m
is 5 which means that a node can have 5 children and internal nodes can contain
maximum 3 children.
o Each node has maximum (m-1) keys.

The root node must contain minimum 1 key and all other nodes must contain
atleast ceiling of m/2 minus 1 keys.

a) & b)Develop a program to insert node and traverse nodes in a binary tree.

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

ALGORITHM:

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

FLOWCHART:

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

CODE:

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

INPUT & OUTPUT (With Different Test Cases):

c) & d) Develop a program to display & delete node in a binary tree.

ALGORITHM:

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

FLOWCHART:

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

CODE:

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

INPUT & OUTPUT (With Different Test Cases):

CONCLUSION:

DISCUSSION AND VIVA VOCE:


Q.1) What is tree?
Q.2) What is B tree and B+ tree?
Q.3) What is Threaded tree?
Q.4) What is BST?
Q.5) How to perform insertion and deletion of node in AVL tree?

REFERENCE:
● Data Structures and Algorithms Concepts, Techniques and Applications, G A
Vijayalakshmi Pai, Mc-Graw Hill Education (India) Ltd. 2008.
● Data Structures Using C, E Balgurusamy, Mc-Graw Hill Education (India) Ltd.

● Data Structures Through C, Yashwant Kanetkar, BPB Publications.

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

S. B. JAIN INSTITUTE OF TECHNOLOGY,


MANAGEMENT & RESEARCH, NAGPUR.

Practical No. 7
Aim: Build Program to implement DFS & BFS:
a) Build Program to implement Depth First Search (DFS).
b) Build Program to implement Breadth First Search (BFS).

Name of Student:
Roll No.:
Semester/Year:
Academic Session:
Date of Performance:
Date of Submission:

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

AIM: Build Program to implement DFS & BFS:


a) Build Program to implement Depth First Search (DFS).
b) Build Program to implement Breadth First Search (BFS).

OBJECTIVE/EXPECTED LEARNING OUTCOME:

● To be able to understand the concept of Graph.


● To be will be able to understand the various types of graphs.
● To be able to implement various searching algorithms in graphs.

Hardware and Software Requirement:


Hardware Requirement:
● Processor : Dual Core
● RAM : 1GB
● Hard Disk Drive : > 80 GB
Software Requirement:
● Operating System – Windows 2007
● IDE – Dev C++
● Online Platform: www.onlineGDB.com

THEORY:
Graph: A graph can be defined as group of vertices and edges that are used to connect these
vertices. A graph can be seen as a cyclic tree, where the vertices (Nodes) maintain any complex
relationship among them instead of having parent child relationship. A graph G can be defined
as an ordered set G(V, E) where V(G) represents the set of vertices and E(G) represents the set
of edges which are used to connect these vertices.

A Graph G(V, E) with 5 vertices (A, B, C, D, E) and six edges ((A,B), (B,C), (C,E), (E,D),
(D,B), (D,A)) is shown in the following figure.

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

Directed and Undirected Graph:


A graph can be directed or undirected. However, in an undirected graph, edges are not
associated with the directions with them. An undirected graph is shown in the above figure
since its edges are not attached with any of the directions. If an edge exists between vertex A
and B then the vertices can be traversed from B to A as well as A to B. In a directed graph,
edges form an ordered pair. Edges represent a specific path from some vertex A to another
vertex B. Node A is called initial node while node B is called terminal node. A directed graph
is shown in the following figure.

Graph Terminology:

Path : A path can be defined as the sequence of nodes that are followed in order to reach some
terminal node V from the initial node U.

Closed Path: A path will be called as closed path if the initial node is same as terminal node.
A path will be closed path if V0=VN.

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

Simple Path: If all the nodes of the graph are distinct with an exception V0=VN, then such path
P is called as closed simple path.

Cycle: A cycle can be defined as the path which has no repeated edges or vertices except the
first and last vertices.

Connected Graph: A connected graph is the one in which some path exists between every
two vertices (u, v) in V. There are no isolated nodes in connected graph.

Complete Graph: A complete graph is the one in which every node is connected with all other
nodes. A complete graph contain n(n-1)/2 edges where n is the number of nodes in the graph.

Weighted Graph: In a weighted graph, each edge is assigned with some data such as length
or weight. The weight of an edge e can be given as w(e) which must be a positive (+) value
indicating the cost of traversing the edge.

Digraph: A digraph is a directed graph in which each edge of the graph is associated with
some direction and the traversing can be done only in the specified direction.

Loop: An edge that is associated with the similar end points can be called as Loop.

Adjacent Nodes : If two nodes u and v are connected via an edge e, then the nodes u and v are
called as neighbours or adjacent nodes.

Degree of the Node: A degree of a node is the number of edges that are connected with that
node. A node with degree 0 is called as isolated node.

Graph representation:
In this article, we will discuss the ways to represent the graph. By Graph representation, we
simply mean the technique to be used to store some graph into the computer's memory.
A graph is a data structure that consist a sets of vertices (called nodes) and edges. There are
two ways to store Graphs into the computer's memory:
o Sequential representation (or, Adjacency matrix representation)
o Linked list representation (or, Adjacency list representation)

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

In sequential representation, an adjacency matrix is used to store the graph. Whereas in linked
list representation, there is a use of an adjacency list to store the graph.

Sequential representation:

In sequential representation, there is a use of an adjacency matrix to represent the mapping


between vertices and edges of the graph. We can use an adjacency matrix to represent the
undirected graph, directed graph, weighted directed graph, and weighted undirected graph.
If adj[i][j] = w, it means that there is an edge exists from vertex i to vertex j with weight w.
An entry Aij in the adjacency matrix representation of an undirected graph G will be 1 if an
edge exists between Vi and Vj. If an Undirected Graph G consists of n vertices, then the
adjacency matrix for that graph is n x n, and the matrix A = [aij] can be defined as -
aij = 1 {if there is a path exists from Vi to Vj}
aij = 0 {Otherwise}
It means that, in an adjacency matrix, 0 represents that there is no association exists between
the nodes, whereas 1 represents the existence of a path between two edges.
If there is no self-loop present in the graph, it means that the diagonal entries of the adjacency
matrix will be 0.

Now, let's see the adjacency matrix representation of an undirected graph.

In the above figure, an image shows the mapping among the vertices (A, B, C, D, E), and this
mapping is represented by using the adjacency matrix.

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

There exist different adjacency matrices for the directed and undirected graph. In a directed
graph, an entry Aij will be 1 only when there is an edge directed from Vi to Vj.

Adjacency matrix for a directed graph:

In a directed graph, edges represent a specific path from one vertex to another vertex. Suppose
a path exists from vertex A to another vertex B; it means that node A is the initial node, while
node B is the terminal node.
Consider the below-directed graph and try to construct the adjacency matrix of it.

In the above graph, we can see there is no self-loop, so the diagonal entries of the adjacent
matrix are 0.

Adjacency matrix for a weighted directed graph:

It is similar to an adjacency matrix representation of a directed graph except that instead of


using the '1' for the existence of a path, here we have to use the weight associated with the edge.
The weights on the graph edges will be represented as the entries of the adjacency matrix. We
can understand it with the help of an example. Consider the below graph and its adjacency
matrix representation. In the representation, we can see that the weight associated with the
edges is represented as the entries in the adjacency matrix.

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

In the above image, we can see that the adjacency matrix representation of the weighted
directed graph is different from other representations. It is because, in this representation, the
non-zero values are replaced by the actual weight assigned to the edges.

Adjacency matrix is easier to implement and follow. An adjacency matrix can be used when
the graph is dense and a number of edges are large.

Though, it is advantageous to use an adjacency matrix, but it consumes more space. Even if
the graph is sparse, the matrix still consumes the same space.

Linked list representation:


An adjacency list is used in the linked representation to store the Graph in the computer's
memory. It is efficient in terms of storage as we only have to store the values for edges.
Let's see the adjacency list representation of an undirected graph.

In the above figure, we can see that there is a linked list or adjacency list for every node of the
graph. From vertex A, there are paths to vertex B and vertex D. These nodes are linked to nodes
A in the given adjacency list.

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

An adjacency list is maintained for each node present in the graph, which stores the node value
and a pointer to the next adjacent node to the respective node. If all the adjacent nodes are
traversed, then store the NULL in the pointer field of the last node of the list.
The sum of the lengths of adjacency lists is equal to twice the number of edges present in an
undirected graph.
Now, consider the directed graph, and let's see the adjacency list representation of that graph.

For a directed graph, the sum of the lengths of adjacency lists is equal to the number of edges
present in the graph.
Now, consider the weighted directed graph, and let's see the adjacency list representation of
that graph.

In the case of a weighted directed graph, each node contains an extra field that is called the
weight of the node.
In an adjacency list, it is easy to add a vertex. Because of using the linked list, it also saves
space.

BFS (Breadth-first search) algorithm:


In this article, we will discuss the BFS algorithm in the data structure. Breadth-first search is
a graph traversal algorithm that starts traversing the graph from the root node and explores all

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

the neighboring nodes. Then, it selects the nearest node and explores all the unexplored nodes.
While using BFS for traversal, any node in the graph can be considered as the root node.
There are many ways to traverse the graph, but among them, BFS is the most commonly used
approach. It is a recursive algorithm to search all the vertices of a tree or graph data structure.
BFS puts every vertex of the graph into two categories - visited and non-visited. It selects a
single node in a graph and, after that, visits all the nodes adjacent to the selected node.

Applications of BFS algorithm:

The applications of breadth-first-algorithm are given as follows -


o BFS can be used to find the neighboring locations from a given source location.
o In a peer-to-peer network, BFS algorithm can be used as a traversal method to find all
the neighboring nodes. Most torrent clients, such as BitTorrent, uTorrent, etc. employ
this process to find "seeds" and "peers" in the network.
o BFS can be used in web crawlers to create web page indexes. It is one of the main
algorithms that can be used to index web pages. It starts traversing from the source page
and follows the links associated with the page. Here, every web page is considered as a
node in the graph.
o BFS is used to determine the shortest path and minimum spanning tree.
o BFS is also used in Cheney's technique to duplicate the garbage collection.
o It can be used in ford-Fulkerson method to compute the maximum flow in a flow
network.

Algorithm:

The steps involved in the BFS algorithm to explore a graph are given as follows -
Step 1: SET STATUS = 1 (ready state) for each node in G
Step 2: Enqueue the starting node A and set its STATUS = 2 (waiting state)
Step 3: Repeat Steps 4 and 5 until QUEUE is empty
Step 4: Dequeue a node N. Process it and set its STATUS = 3 (processed state).
Step 5: Enqueue all the neighbours of N that are in the ready state (whose STATUS = 1)
and set
their STATUS = 2
(waiting state)

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

[END OF LOOP]
Step 6: EXIT

Example of BFS algorithm:

Now, let's understand the working of BFS algorithm by using an example. In the example given
below, there is a directed graph having 7 vertices.

In the above graph, minimum path 'P' can be found by using the BFS that will start from Node
A and end at Node E. The algorithm uses two queues, namely QUEUE1 and QUEUE2.
QUEUE1 holds all the nodes that are to be processed, while QUEUE2 holds all the nodes that
are processed and deleted from QUEUE1.
Now, let's start examining the graph starting from Node A.
Step 1 - First, add A to queue1 and NULL to queue2.
1. QUEUE1 = {A}
2. QUEUE2 = {NULL}
Step 2 - Now, delete node A from queue1 and add it into queue2. Insert all neighbors of node
A to queue1.
1. QUEUE1 = {B, D}
2. QUEUE2 = {A}
Step 3 - Now, delete node B from queue1 and add it into queue2. Insert all neighbors of node
B to queue1.
1. QUEUE1 = {D, C, F}
2. QUEUE2 = {A, B}
Step 4 - Now, delete node D from queue1 and add it into queue2. Insert all neighbors of node
D to queue1. The only neighbor of Node D is F since it is already inserted, so it will not be
inserted again.
1. QUEUE1 = {C, F}
2. QUEUE2 = {A, B, D}

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

Step 5 - Delete node C from queue1 and add it into queue2. Insert all neighbors of node C to
queue1.
1. QUEUE1 = {F, E, G}
2. QUEUE2 = {A, B, D, C}
Step 5 - Delete node F from queue1 and add it into queue2. Insert all neighbors of node F to
queue1. Since all the neighbors of node F are already present, we will not insert them again.
1. QUEUE1 = {E, G}
2. QUEUE2 = {A, B, D, C, F}
Step 6 - Delete node E from queue1. Since all of its neighbors have already been added, so we
will not insert them again. Now, all the nodes are visited, and the target node E is encountered
into queue2.
1. QUEUE1 = {G}
2. QUEUE2 = {A, B, D, C, F, E}

Complexity of BFS algorithm:

Time complexity of BFS depends upon the data structure used to represent the graph. The time
complexity of BFS algorithm is O(V+E), since in the worst case, BFS algorithm explores every
node and edge. In a graph, the number of vertices is O(V), whereas the number of edges is
O(E). The space complexity of BFS can be expressed as O(V), where V is the number of
vertices.

DFS (Depth First Search) algorithm:


In this article, we will discuss the DFS algorithm in the data structure. It is a recursive algorithm
to search all the vertices of a tree data structure or a graph. The depth-first search (DFS)
algorithm starts with the initial node of graph G and goes deeper until we find the goal node or
the node with no children.
Because of the recursive nature, stack data structure can be used to implement the DFS
algorithm. The process of implementing the DFS is similar to the BFS algorithm.
The step by step process to implement the DFS traversal is given as follows -
1. First, create a stack with the total number of vertices in the graph.
2. Now, choose any vertex as the starting point of traversal, and push that vertex into the
stack.

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

3. After that, push a non-visited vertex (adjacent to the vertex on the top of the stack) to
the top of the stack.
4. Now, repeat steps 3 and 4 until no vertices are left to visit from the vertex on the stack's
top.
5. If no vertex is left, go back and pop a vertex from the stack.
6. Repeat steps 2, 3, and 4 until the stack is empty.

Applications of DFS algorithm:

The applications of using the DFS algorithm are given as follows –


● DFS algorithm can be used to implement the topological sorting.
● It can be used to find the paths between two vertices.
● It can also be used to detect cycles in the graph.
● DFS algorithm is also used for one solution puzzles.
● DFS is used to determine if a graph is bipartite or not.

Algorithm:

Step 1: SET STATUS = 1 (ready state) for each node in G


Step 2: Push the starting node A on the stack and set its STATUS = 2 (waiting state)
Step 3: Repeat Steps 4 and 5 until STACK is empty
Step 4: Pop the top node N. Process it and set its STATUS = 3 (processed state)
Step 5: Push on the stack all the neighbors of N that are in the ready state (whose STATUS
= 1) and set their STATUS = 2 (waiting state)
[END OF LOOP]
Step 6: EXIT

Example of DFS algorithm:

Now, let's understand the working of the DFS algorithm by using an example. In the example
given below, there is a directed graph having 7 vertices.

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

Now, let's start examining the graph starting from Node H.


Step 1 - First, push H onto the stack.
1. STACK: H
Step 2 - POP the top element from the stack, i.e., H, and print it. Now, PUSH all the neighbors
of H onto the stack that are in ready state.
1. Print: H]STACK: A
Step 3 - POP the top element from the stack, i.e., A, and print it. Now, PUSH all the neighbors
of A onto the stack that are in ready state.
1. Print: A
2. STACK: B, D
Step 4 - POP the top element from the stack, i.e., D, and print it. Now, PUSH all the neighbors
of D onto the stack that are in ready state.
1. Print: D
2. STACK: B, F
Step 5 - POP the top element from the stack, i.e., F, and print it. Now, PUSH all the neighbors
of F onto the stack that are in ready state.
1. Print: F
2. STACK: B
Step 6 - POP the top element from the stack, i.e., B, and print it. Now, PUSH all the neighbors
of B onto the stack that are in ready state.
1. Print: B
2. STACK: C
Step 7 - POP the top element from the stack, i.e., C, and print it. Now, PUSH all the neighbors
of C onto the stack that are in ready state.
1. Print: C

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

2. STACK: E, G
Step 8 - POP the top element from the stack, i.e., G and PUSH all the neighbors of G onto the
stack that are in ready state.
1. Print: G
2. STACK: E
Step 9 - POP the top element from the stack, i.e., E and PUSH all the neighbors of E onto the
stack that are in ready state.
1. Print: E
2. STACK:
Now, all the graph nodes have been traversed, and the stack is empty.

Complexity of Depth-first search algorithm: The time complexity of the DFS algorithm
is O(V+E), where V is the number of vertices and E is the number of edges in the graph. The
space complexity of the DFS algorithm is O(V).

a) Build Program to implement Depth First Search (DFS).


ALGORITHM:

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

FLOWCHART:

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

CODE:

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

INPUT & OUTPUT (With Different Test Cases):

a) Build Program to implement Breadth First Search (BFS).

ALGORITHM:

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

FLOWCHART:

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

CODE:

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

INPUT & OUTPUT (With Different Test Cases):

CONCLUSION:

DISCUSSION AND VIVA VOCE:


Q.1) What is a graph?
Q.2) How tree is different from graph?
Q.3) What are types of graph?
Q.4) What are techniques for searching in a graph?
Q.5) How to perform insertion and deletion of node in a graph?

REFERENCE:
● Data Structures and Algorithms Concepts, Techniques and Applications, G A
Vijayalakshmi Pai, Mc-Graw Hill Education (India) Ltd. 2008.
● Data Structures Using C, E Balgurusamy, Mc-Graw Hill Education (India) Ltd.

● Data Structures Through C, Yashwant Kanetkar, BPB Publications.

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

S. B. JAIN INSTITUTE OF TECHNOLOGY,


MANAGEMENT & RESEARCH, NAGPUR.

Practical No. 9
Aim: Develop a program to implement a Hash table:

a) Build a program to insert an element in a hash table.


b) Build a program to display elements of a hash table.
c) Build a program to Search an element of a hash table.
d) Build a program to delete an element of a hash table.

Name of Student:
Roll No.:
Semester/Year:
Academic Session:
Date of Performance:
Date of Submission:

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

AIM: Develop a program to implement a Hash table:

a) Build a program to insert an element in a hash table.


b) Build a program to display elements of a hash table.
c) Build a program to Search an element of a hash table.
d) Build a program to delete an element of a hash table.

OBJECTIVE/EXPECTED LEARNING OUTCOME:

● To be able to understand the concept of Hashing.


● To be will be able to understand the various types of hashing techniques.
● To be able to implement various hashing techniques.

Hardware and Software Requirement:


Hardware Requirement:
● Processor : Dual Core
● RAM : 1GB
● Hard Disk Drive : > 80 GB
Software Requirement:
● Operating System – Windows 2007
● IDE – Dev C++
● Online Platform: www.onlineGDB.com

THEORY:
What is Hashing?

Hashing is a technique or process of mapping keys, and values into the hash table by using a
hash function. It is done for faster access to elements. The efficiency of mapping depends on
the efficiency of the hash function used.

Let a hash function H(x) maps the value x at the index x%10 in an Array. For example if the
list of values is [11,12,13,14,15] it will be stored at positions {1,2,3,4,5} in the array or Hash
table respectively.

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

Suppose we want to design a system for storing employee records with phone
numbers(as keys). And we want the following queries to be performed efficiently:

1. Insert a phone number and corresponding information.


2. Search a phone number and fetch the information.
3. Delete a phone number and related information.

We can think of using the following data structures to maintain information about different
phone numbers.

1. Array of phone numbers and records.


2. Linked List of phone numbers and records.
3. Balanced binary search tree with phone numbers as keys.
4. Direct Access Table.

For arrays and linked lists, we need to search in a linear fashion, which can be costly in
practice. If we use arrays and keep the data sorted, then a phone number can be searched in
O(Logn) time using Binary Search, but insert and delete operations become costly as we have
to maintain sorted order.

With balanced binary search tree, we get moderate search, insert and delete times. All of
these operations can be guaranteed to be in O(Logn) time.

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

Another solution that one can think of is to use a direct access table where we make a big
array and use phone numbers as index in the array. An entry in array is NIL if phone number
is not present, else the array entry stores pointer to records corresponding to phone number.
Time complexity wise this solution is the best among all, we can do all operations in O(1) time.
For example to insert a phone number, we create a record with details of given phone number,
use phone number as index and store the pointer to the created record in table.
This solution has many practical limitations. First problem with this solution is extra space
required is huge. For example if phone number is n digits, we need O(m * 10n) space for table
where m is size of a pointer to record. Another problem is an integer in a programming language
may not store n digits.

Due to above limitations Direct Access Table cannot always be used. Hashing is the solution
that can be used in almost all such situations and performs extremely well compared to above
data structures like Array, Linked List, Balanced BST in practice. With hashing we get O(1)
search time on average (under reasonable assumptions) and O(n) in worst case. Now let us
understand what hashing is.

Why to use Hashing?


If you observe carefully, in a balanced binary search tree, if we try to search , insert or delete
any element then the time complexity for the same is O(logn). Now there might be a situation
when our applications want to do the same operations in a faster way i.e. in a more optimized
way and here hashing comes into play. In hashing, all the above operations can be performed
in O(1) i.e. constant time. It is important to understand that the worst case time complexity for
hashing remains O(n) but the average case time complexity is O(1).
Now let us understand a few basic operations of hashing.

Basic Operations:
● HashTable: This operation is used in order to create a new hash table.
● Delete: This operation is used in order to delete a particular key-value pair from the hash
table.
● Get: This operation is used in order to search a key inside the hash table and return the
value that is associated with that key.
● Put: This operation is used in order to insert a new key-value pair inside the hash table.

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

● DeleteHashTable: This operation is used in order to delete the hash table

Hashing Components:
1) Hash Table: An array that stores pointers to records corresponding to a given phone
number. An entry in hash table is NIL if no existing phone number has hash function
value equal to the index for the entry. In simple terms, we can say that hash table is a
generalization of array. Hash table gives the functionality in which a collection of data
is stored in such a way that it is easy to find those items later if required. This makes
searching of an element very efficient.

2) Hash Function: A function that converts a given big phone number to a small practical
integer value. The mapped integer value is used as an index in hash table. So, in simple
terms we can say that a hash function is used to transform a given key into a specific
slot index. Its main job is to map each and every possible key into a unique slot index.
If every key is mapped into a unique slot index, then the hash function is known as a
perfect hash function. It is very difficult to create a perfect hash function but our job as
a programmer is to create such a hash function with the help of which the number of
collisions are as few as possible. Collision is discussed ahead.

A good hash function should have following properties:


1. Efficiently computable.
2. Should uniformly distribute the keys (Each table position equally likely for each).
3. Should minimize collisions.
4. Should have a low load factor(number of items in table divided by size of the
table).

For example for phone numbers a bad hash function is to take first three digits. A better function
is consider last three digits. Please note that this may not be the best hash function. There may
be better ways.

What is Collision?
Since a hash function gets us a small number for a key which is a big integer or string, there is
a possibility that two keys result in the same value. The situation where a newly inserted key

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

maps to an already occupied slot in the hash table is called collision and must be handled using
some collision handling technique.

Collision Handling: Since a hash function gets us a small number for a big key, there is
possibility that two keys result in same value. The situation where a newly inserted key maps
to an already occupied slot in hash table is called collision and must be handled using some
collision handling technique. Following are the ways to handle collisions:

● Chaining:The idea is to make each cell of hash table point to a linked list of records that
have same hash function value. Chaining is simple, but requires additional memory outside
the table.
● 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.

Separate Chaining:
The idea behind separate chaining is to implement the array as a linked list called a chain.
Separate chaining is one of the most popular and commonly used techniques in order to handle
collisions.

The linked list data structure is used to implement this technique. So what happens is, when
multiple elements are hashed into the same slot index, then these elements are inserted into a
singly-linked list which is known as a chain.

Here, all those elements that hash into the same slot index are inserted into a linked list. Now,
we can use a key K to search in the linked list by just linearly traversing. If the intrinsic key for
any entry is equal to K then it means that we have found our entry. If we have reached the end
of the linked list and yet we haven’t found our entry then it means that the entry does not exist.
Hence, the conclusion is that in separate chaining, if two different elements have the same hash
value then we store both the elements in the same linked list one after the other.

Example: Let us consider a simple hash function as “key mod 7” and a sequence of keys as
50, 700, 76, 85, 92, 73, 101

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

Open Addressing:
Like separate chaining, open addressing is a method for handling collisions. In Open
Addressing, all elements are stored in the hash table itself. So at any point, the size of the table
must be greater than or equal to the total number of keys (Note that we can increase table size
by copying old data if needed). This approach is also known as closed hashing. This entire
procedure is based upon probing. We will understand the types of probing ahead:

● Insert(k): Keep probing until an empty slot is found. Once an empty slot is found, insert
k.
● Search(k): Keep probing until the slot’s key doesn’t become equal to k or an empty slot
is reached.
● Delete(k): Delete operation is interesting. If we simply delete a key, then the search may
fail. So slots of deleted keys are marked specially as “deleted”.
The insert can insert an item in a deleted slot, but the search doesn’t stop at a deleted
slot.

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

Different ways of Open Addressing:

Linear Probing:
In linear probing, the hash table is searched sequentially that starts from the original location
of the hash. If in case the location that we get is already occupied, then we check for the next
location.

The function used for rehashing is as follows: rehash(key) = (n+1)%table-size.

For example, The typical gap between two probes is 1 as seen in the example below:
Let hash(x) be the slot index computed using a hash function and S be the table size
If slot hash(x) % S is full, then we try (hash(x) + 1) % S
If (hash(x) + 1) % S is also full, then we try (hash(x) + 2) % S
If (hash(x) + 2) % S is also full, then we try (hash(x) + 3) % S
…………………………………………..
…………………………………………..

Let us consider a simple hash function as “key mod 7” and a sequence of keys as 50, 700, 76,
85, 92, 73, 101.

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

Challenges in Linear Probing :


● Primary Clustering: One of the problems with linear probing is Primary clustering, many
consecutive elements form groups and it starts taking time to find a free slot or to search for an
element.
● Secondary Clustering: Secondary clustering is less severe, two records only have the same
collision chain (Probe Sequence) if their initial position is the same.
Example: Let us consider a simple hash function as “key mod 5” and a sequence of keys that
are to be inserted are 50, 70, 76, 93.
● Step1: First draw the empty hash table which will have a possible range of hash values from 0
to 4 according to the hash function provided.

Hash table

● Step 2: Now insert all the keys in the hash table one by one. The first key is 50. It will map to
slot number 0 because 50%5=0. So insert it into slot number 0.

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

Insert key 50 in the hash table

● Step 3: The next key is 70. It will map to slot number 0 because 70%5=0 but 50 is already at
slot number 0 so, search for the next empty slot and insert it.

Insert key 70 in the hash table

● Step 4: The next key is 76. It will map to slot number 1 because 76%5=1 but 70 is already at
slot number 1 so, search for the next empty slot and insert it.

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

Insert key 76 in the hash table

● Step 5: The next key is 93 It will map to slot number 3 because 93%5=3, So insert it into slot
number 3.

Insert key 93 in the hash table

Quadratic Probing:

If you observe carefully, then you will understand that the interval between probes will increase
proportionally to the hash value. Quadratic probing is a method with the help of which we can
solve the problem of clustering that was discussed above. This method is also known as
the mid-square method. In this method, we look for the i2‘th slot in the ith iteration. We
always start from the original hash location. If only the location is occupied then we check the
other slots.
let hash(x) be the slot index computed using hash function.

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

If slot hash(x) % S is full, then we try (hash(x) + 1*1) % S


If (hash(x) + 1*1) % S is also full, then we try (hash(x) + 2*2) % S
If (hash(x) + 2*2) % S is also full, then we try (hash(x) + 3*3) % S
…………………………………………..
…………………………………………..

Example: Let us consider table Size = 7, hash function as Hash(x) = x % 7 and collision
resolution strategy to be f(i) = i2 . Insert = 22, 30, and 50.

● Step 1: Create a table of size 7.

Hash table

Step 2 – Insert 22 and 30


● Hash(22) = 22 % 7 = 1, Since the cell at index 1 is empty, we can easily insert 22 at
slot 1.
● Hash(30) = 30 % 7 = 2, Since the cell at index 2 is empty, we can easily insert 30 at
slot 2.

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

Insert keys 22 and 30 in the hash table

Step 3: Inserting 50

● Hash(50) = 50 % 7 = 1
● In our hash table slot 1 is already occupied. So, we will search for slot 1+12, i.e. 1+1 = 2,
● Again slot 2 is found occupied, so we will search for cell 1+22, i.e.1+4 = 5,
● Now, cell 5 is not occupied so we will place 50 in slot 5.

Insert key 50 in the hash table

Double Hashing:
The intervals that lie between probes are computed by another hash function. Double hashing
is a technique that reduces clustering in an optimized way. In this technique, the increments for

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

the probing sequence are computed by using another hash function. We use another hash
function hash2(x) and look for the i*hash2(x) slot in the ith rotation.
let hash(x) be the slot index computed using hash function.

If slot hash(x) % S is full, then we try (hash(x) + 1*hash2(x)) % S


If (hash(x) + 1*hash2(x)) % S is also full, then we try (hash(x) + 2*hash2(x)) % S
If (hash(x) + 2*hash2(x)) % S is also full, then we try (hash(x) + 3*hash2(x)) % S
…………………………………………..
…………………………………………..

Example: Insert the keys 27, 43, 692, 72 into the Hash Table of size 7. where first hash-
function is h1(k) = k mod 7 and second hash-function is h2(k) = 1 + (k mod 5)
● Step 1: Insert 27
● 27 % 7 = 6, location 6 is empty so insert 27 into 6 slot.

Insert key 27 in the hash table

● Step 2: Insert 43
● 43 % 7 = 1, location 1 is empty so insert 43 into 1 slot.

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

Insert key 43 in the hash table

● Step 3: Insert 692


● 692 % 7 = 6, but location 6 is already being occupied and this is a collision
● So we need to resolve this collision using double hashing.
hnew = [h1(692) + i * (h2(692)] % 7
= [6 + 1 * (1 + 692 % 5)] % 7
= 9% 7
=2
Now, as 2 is an empty slot,
so we can insert 692 into 2nd slot.

Insert key 692 in the hash table

Step 4: Insert 72
● 72 % 7 = 2, but location 2 is already being occupied and this is a collision.

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

● So we need to resolve this collision using double hashing.


hnew = [h1(72) + i * (h2(72)] % 7
= [2 + 1 * (1 + 72 % 5)] % 7
=5%7
= 5,
Now, as 5 is an empty slot,
so we can insert 72 into 5th slot.

Insert key 72 in the hash table

Comparison of the above three:


● Linear probing has the best cache performance but suffers from clustering. One more
advantage of Linear probing is easy to compute.
● Quadratic probing lies between the two in terms of cache performance and clustering.
● Double hashing has poor cache performance but no clustering. Double hashing requires
more computation time as two hash functions need to be computed.

S.No. Separate Chaining Open Addressing

Open Addressing requires more


1. Chaining is Simpler to implement. computation.

In chaining, Hash table never fills up, we In open addressing, table may become
2. can always add more elements to chain. full.

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

S.No. Separate Chaining Open Addressing

Chaining is Less sensitive to the hash Open addressing requires extra care to
3. function or load factors. avoid clustering and load factor.

Chaining is mostly used when it is Open addressing is used when the


unknown how many and how frequently frequency and number of keys is
4. keys may be inserted or deleted. known.

Open addressing provides better cache


Cache performance of chaining is not good performance as everything is stored in
5. as keys are stored using linked list. the same table.

Wastage of Space (Some Parts of hash table In Open addressing, a slot can be used
6. in chaining are never used). even if an input doesn’t map to it.

7. Chaining uses extra space for links. No links in Open addressing

Note: Cache performance of chaining is not good because when we traverse a Linked List, we
are basically jumping from one node to another, all across the computer’s memory. For this
reason, the CPU cannot cache the nodes which aren’t visited yet, this doesn’t help us. But with
Open Addressing, data isn’t spread, so if the CPU detects that a segment of memory is
constantly being accessed, it gets cached for quick access.

Hash Table:
Hash table is one of the most important data structures that uses a special function known as a
hash function that maps a given value with a key to access the elements faster.
A Hash table is a data structure that stores some information, and the information has basically
two main components, i.e., key and value. The hash table can be implemented with the help of
an associative array. The efficiency of mapping depends upon the efficiency of the hash
function used for mapping.

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

For example, suppose the key value is John and the value is the phone number, so when we
pass the key value in the hash function shown as below:
Hash(key)= index;
When we pass the key in the hash function, then it gives the index.
Hash(john) = 3;
The above example adds the john at the index 3.

a) Build a program to insert & display elements in a hash table.

ALGORITHM:

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

FLOWCHART:

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

CODE:

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

INPUT & OUTPUT (With Different Test Cases):

c) & d) Build a program to search & delete elements of a hash table.

ALGORITHM:

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

FLOWCHART:

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

CODE:

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

INPUT & OUTPUT (With Different Test Cases):

CONCLUSION:

DISCUSSION AND VIVA VOCE:


Q.1) What is hashing?
Q.2) What are various techniques of hashing?
Q.3) Why collision occurs in hashing?
Q.4) How to handle collision in hashing?
Q.5) What a hash table contains?

REFERENCE:
● Data Structures and Algorithms Concepts, Techniques and Applications, G A
Vijayalakshmi Pai, Mc-Graw Hill Education (India) Ltd. 2008.
● Data Structures Using C, E Balgurusamy, Mc-Graw Hill Education (India) Ltd.

● Data Structures Through C, Yashwant Kanetkar, BPB Publications.

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

S. B. JAIN INSTITUTE OF TECHNOLOGY,


MANAGEMENT & RESEARCH, NAGPUR.

Practical No. 9
(Post Lab: Mini Project**)
Project Title:

Name of Student:

Roll No.:

Semester/Year:

Academic Session:

Date of Demonstration:

Date of Submission of Report:

**Note: A separate Project Report of your project is to be prepared and


submitted to your respective Lab Course teacher.

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur


Data Structure & Algorithm Lab (PCCCS307P)

Department of Computer Science & Engineering, S.B.J.I.T.M.R., Nagpur

You might also like