0% found this document useful (0 votes)
41 views

DSA MasterLabManual Fall2024

Uploaded by

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

DSA MasterLabManual Fall2024

Uploaded by

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

DHA Suffa University

Master Manual

Data Structures and Algorithms Lab

CS-2001L

Fall 2024
Index
Approval from
S.No Title
teacher

Introduction to Data Structures and getting started


1
with Java

2 Implementation of array processing

3 Implementation of Singly Linked List

4 Implementation of Doubly Linked List

5 Implementation of Circular Linked List

6 Implementation of Stack

7 Implementation of Queue

8 Implementation of Binary Tree

9 Implementation of Binary Search Tree

10 Implementation of AVL Trees

11 Implementation of Graphs

12 Implementation of Merge, Selection and Quick Sort

13 Implementation of Bubble Sort

14 Implementation of HashTable

Lab Teacher Name

Lab Teacher Signature


DHA SUFFA UNIVERSITY
Department of Computer Science
CS-2001L Data Structures and Algorithms Lab
FALL 2023
LAB 01

Objective(s)
Introduction to Data Structures and getting started with Java, including
 Classes and Objects
 Input, Output
 Conditional Statements
 Loops
 Arrays (introduction)

Theory
Data Structure
Data Structure is a way of collecting and organizing data in such a way that we can perform operations
on these data in an effective way. Data Structures is about rendering data elements in terms of some
relationship, for better organization and storage.
Data Structures are structures programmed to store ordered data, so that various operations can be
performed on it easily. It represents the knowledge of data to be organized in memory. It should be
designed and implemented in such a way that it reduces the complexity and increases the efficiency.

Algorithm:
A step-by-step procedure for solving a problem or accomplishing some end especially by a computer
For example: a search algorithm.

Requirement for Hello Java Example


For executing any java program, you need to
 install the JDK if you don't have installed it, download the JDK and install it.
 http://www.oracle.com/technetwork/java/javase/downloads/index.html
 set path of the jdk/bin directory. http://www.javatpoint.com/how-to-set-path-in-java
 create the java program
 compile and run the java program

1
Simple Program in Java

In this page, we will learn how to write the simple program of java. We can write a simple
hello java program easily after installing the JDK.

To create a simple java program, you need to create a class that contains main method.
Let's understand the requirement first.

Creating hello java example

Let's create the hello java program:

class A {
public static void main(String args[]){
System.out.println("Hello Java");
}
}
To write the simple program, open notepad by start menu -> notepad and write
simple program as displayed below:

2
As displayed in the above diagram, write the simple program of java in notepad and saved it
as A.java. To compile and run this program, you need to open command prompt by start
menu -> command prompt.
To compile and run the above program, go to your current directory first; my current
directory is D:\. Write here:

To compile: javac A.java (where A is class name)


To execute: java A

Classes and Objects


In more complex Java programs, the primary “actors” are objects. Every object is
an instance of a class, which serves as the type of the object and as a blueprint,
defining the data which the object stores and the methods for accessing and modifying
that data. The critical members of a class in Java are the following:

3
• Instance variables, which are also called fields, represent the data associated
with an object of a class. Instance variables must have a type, which can
either be a base type (such as int, float, or double) or any class type (also
known as a reference type for reasons we soon explain).
• Methods, in Java are blocks of code that can be called to perform actions
(similar to functions and procedures in other high-level languages). Methods
can accept parameters as arguments, and their behavior may depend on the
object upon which they are invoked and the values of any parameters that are
passed. A method that returns information to the caller without changing any
instance variables is known as an accessor method, while an update method
is one that may change one or more instance variables when called.
For the purpose of illustration, Code Fragment 1.2 provides a complete definition
of a very simple class named Counter, to which we will refer during the
remainder of this section.

Creating and Using Objects


Before we explore the intricacies of the syntax for our Counter class definition, we
prefer to describe how Counter instances can be created and used. To this end,
Code Fragment 1.3 presents a new class named CounterDemo.

4
Java Scanner Example to get input from console and printing output using System class

Let's see the simple example of the Java Scanner class which reads the int, string and
double value as an input:

Conditional Statements

The Java if statement is used to test the condition. It checks boolean condition: true or false. There are
various types of if statement in java.

o if statement
o if-else statement
o if-else-if ladder
o nested if statement

Example of if else if ladder

5
Loops

There are four types of loop in java.

o For Loop
o For-each or Enhanced For Loop
o While loop
o Do while loop

Example of for loop

6
Example of single dimensional java array

Let's see the simple example of java array, where we are going to declare, instantiate,
initialize and traverse an array.

LAB TASK
Q1. Swap the values of two instance variables without using third variable.
Q2. Write a Java program that reads in two floating-point numbers and tests whether they are
the same up to three decimal places.
Q3. Write a program that accepts three numbers from the user and prints "increasing" if the
numbers are in increasing order, "decreasing" if the numbers are in decreasing order, and
"Neither increasing nor decreasing order" otherwise. (create a method to solve this problem)

Submission Guidelines
 Write your codes in different notepad (.java) files.
 Place all files in a folder named your roll number e.g. cs162001.
 Compress all files into one (.zip) file named same as your roll number.
 Upload it on LMS / email at [email protected]
 -100 policies for plagiarism

7
DHA SUFFA UNIVERSITY
Department of Computer Science
CS-2001L
Data Structures & Algorithms Lab
Fall 2023
LAB 02

Objective(s)
Implementation of the following array processing algorithms:
 Traversing an array
 insert
 delete
 search
Implementation of matrix operations using two dimensional arrays

Theory
Traversing
Our basic operation starts with visiting each element of the array exactly once and in order.

Insert
Given an array of length N, we have to insert an element in array at index i (0 <= i <= N-1). After
inserting an element, the number of elements in array will increase by one.

Delete
Given an array of length N, we have to delete an element at index i (0 <= i <= N-1) from an
array. After deleting an element, the number of elements in array will decrease by one.
Search
Given an unsorted array of N integers (N > 0) and an integer value v, write the function that
returns zero-based index in the array at which the value v is located. Function should return
negative value if array does not contain v.

Algorithms
Algorithm A1: travers(arr[])
1. Start
2. for i = 0 to N repeat step 3
3. PRINT arr[i]

LAB # 02
8
Algorithm A2: insert(LA , K , ITEM)
1. Start
2. Set J = N
3. Set N = N+1
4. Repeat steps 5 and 6 while J >= K
5. Set LA[J+1] = LA[J]
6. Set J = J•1
7. Set LA[K] = ITEM
8. Stop

Algorithm A3: delete(LA , K)


1. Start
2. Set J = K
3. Repeat steps 4 and 5 while J < N
4. Set LA[J•1] = LA[J]
5. Set J = J+1
6. Set N = N•1
7. Stop

Algorithm A4: search(LA , ITEM)


1. Start
2. Set J = 0
3. Repeat steps 4 and 5 while J < N
4. IF LA[J] is equal ITEM THEN GOTO STEP 6
5. Set J = J +1
6. PRINT J, ITEM
Stop

Task (to be performed during lab session):


Implement the algorithms A1-A4 in Java with test cases of your own choice.

LAB # 02
9
Two dimensional Arrays
We have seen a one-dimensional array

The array elements are selected using a one index. A two-dimensional array is an array where
its elements are selected (identified) using two indices.

Thus, every element in array a is identified by an element name of the form a[ i ][ j ], where a is
the name of the array, and i and j are the subscripts that uniquely identify each element in a.

Initializing and Accessing Two-Dimensional Arrays

LAB # 02
10
Matrix Addition
We consider two input matrices A and B of order n x n. We need to computer C = A + B,
where C is of order n x n.
To add two matrixes sufficient and necessary condition is "dimensions of matrix A =
dimensions of matrix B".

Matrix Subtraction
We consider two input matrices A and B of order n x n. We need to computer C = A-B,
where C is of order n x n.
To add two matrixes sufficient and necessary condition is "dimensions of matrix A =
dimensions of matrix B".

Matrix Multiplication
We consider two input matrices A and B of order n x n. We need to computer C = A x B,
where, C is of order n 0x n.
To multiply two matrixes sufficient and necessary condition is “the number of columns in
A must equal the number of rows in B.”

Algorithm:
Algorithm A5: addMatrix(a[][], b[][], c[][]))
1. Start
2. for I = 0 to n-1 Repeat 3 to 4
3. for j = 0 to n-1 Repeat 4
4. c[i][j] = a[i][j] + b[i][j]
5. Stop

Algorithm A6: subMatrix(a[][], b[][], c[][]))


1. Start
2. for I = 0 to n-1 Repeat 3 to 4
3. for j = 0 to n-1 Repeat 4
4. c[i][j] = a[i][j] b[i][j]
5. Stop

LAB # 02
11
Algorithm A7: mulMatrix(a[][], b[][], c[][]))
1. Start
2. For i = 0 to n-1 Repeat 3 to 6
3. For j = 0 to n-1 Repeat 4 to 6
4. C[i, j] == 0
5. for k = 0 to n-1 Repeat 6
6. c[i][j] = c[i][j] + a[i][k]*b[k][j]
Stop

Task (to be performed during lab session):


Implement the algorithms A5-A7 in Java with test cases of your own choice.

LAB # 02
12
LAB TASKS

Q1. Write a program for: insert(LA, K, ITEM)


a) K is not out of range
b) Item must be positive integer
c) Check user's entered ITEM at index K is greater or less than in an array at index K, if less than
insert it into the array otherwise not perform any operation, and prints the message 'ITEM’ at
index k is greater than user's entered ‘ITEM'.

Q2. Write a program for: search(LA,ITEM) in Java


a) Search whether the user's entered item is exist or not in the array if exist perform following
b) Print two right neighbors(item/value) in case no right neighbor print message 'no right neighbor'
c) Print two left neighbors(item/value) in case no left neighbor print message 'no left neighbor'

Q3.
a) Let A be an array of size n≥2 containing integers from 1 to n−1 inclusive, one of which is
repeated. Write a program for finding the integer in A that is repeated.
b) Let B be an array of size n≥6 containing integers from 1 to n−5 inclusive, five of which are
repeated. Write a program for finding the five integers in B that are repeated.

TWO DIMENSIONAL ARRAYS

Q1. Write a program that finds the transpose of a 2D matrix.


Q2. Write functions for square matrix to calculate
1. Left diagonal sum
2. Right diagonal sum

Submission Guidelines
 Write your codes in different notepad (.java) files.
 Place all files in a folder named your roll number e.g. cs162001.
 Compress all files into one (.zip) file named same as your roll number.
 Upload it on LMS
 -100 policies for plagiarism

LAB # 02
13
DHA SUFFA UNIVERSITY
Department of Computer Science
CS-2001 L
Data Structures & Algorithms Lab
Fall 2023
LAB 03
Objective:
Implementation of Singly Linked List using the below operations:
 Traversal
 Insert
 Delete
 Search

Theory:
Single Linked List
Single linked list is a sequence of elements in which every element has link to its next
element in the sequence.
In any single linked list, the individual element is called as "Node". Every "Node" contains
two fields, data and next. The data field is used to store actual value of that node and
next field is used to store the address of the next node in the sequence.

In Java, Linked List can be represented as a class and a Node as a separate class. The
Linked List class contains a reference of Node class type.

14
In Singly linked list you can perform following function.
 Traversal
 Insert
 Delete
 Search

Creating Linked List

15
Traversing a linked list

//function call in main method

Inserting a node in linked list


 Add a node at front

16
Java Code:

 Add a node after a given node

Java Code:

17
Task:
Write a Java program to implement insertion a node at the end of the linked list.

Deleting a node from linked list

Searching a node from linked list

18
TASKS
Perform the following tasks using singly linked list(SLL), create separate function for each
task
1. Find the length of a given SLL.
2. Print the middle node of a given SLL.
3. Reverse a given SLL. (A copy of original SLL should be retained).
4. Remove duplicates from a sorted SLL .
5. Merge two sorted SLL .
6. Delete complete SLL.

Submission Guidelines
 Write your codes in different notepad (.java) files with question number e.g.
Q1.java
 Place all files in a folder named your roll number e.g. cs162XXX.
 Compress all files into one (.zip) file named same as your roll number.
 Upload it on LMS
 -100 policies for plagiarism

19
DHA SUFFA UNIVERSITY
Department of Computer Science
CS-2001L
Data Structures & Algorithms Lab
Fall 2023
LAB 04
Objective:
Implementation of Doubly Linked List using the below operations:
 Traverse
 Insert
 Delete

Theory:
For creating a node, you can use the following nested class called Node.

Java Code

20
Creating Nodes in main method

Traversing a Doubly Linked List (forward)


 Check whether list is Empty (head == NULL)
 If it is Empty, then display 'List is Empty!!!' and terminate the function.
 If it is not Empty, then define a Node ‘current’ and initialize with head.
 Using a loop print current->data and update current to current->next until current is
not equal to null.

Java Code

Task
Write a Java program to traverse a doubly linked list (backward). Starting from tail.

21
Inserting a node at the beginning of the list
 Check whether list is Empty (head == NULL)
 If it is Empty then, assign NULL to newNode → next and newNode to head.
 If it is not Empty then, assign head to newNode → next and newNode to head.

Java Code

Inserting a node at the end of the list


 Create a new node.
 Assign new node to tail->next and tail->new node

Task:
Write a Java program to implement insertion of a node at the end of the doubly linked
list.

Inserting After specific node in the list


insertAfter(Node prev_node,int new_data)
 Create a new node with given new_data.
 Create a node temp, assign prev_node->next to temp.
 Assign new node to prev_node->next
 Assign prev_node to new node->previous
 Assign temp to new node->next

22
Java Code

Task:
Write a Java program to implement insertion of a node before specific node.
insertBefore(Node next_node,int new_data)

Deleting from Beginning of the list


 Check whether list is Empty (head == NULL)
 If it is Empty then, display 'List is Empty!!! Deletion is not possible' and terminate the
function.
 If it is not Empty then, define a Node pointer 'temp' and initialize with head.
 Assign head->next to head.

Java Code

Task:
Write a Java program to implement deletion of the last node in doubly linked list.

Deleting a Specific Node from the list

23
TASK
Create a text editor using doubly linked list, which includes the text area in which user
can enter data, delete and modify it. Proper menu at the top of the editor is not needed.

Submission Guidelines
 Write your code in notepad file (.java) and build the project to executable jar file.
 Place all files in a folder named your roll number e.g. cs162XXX.
 Compress all files into one (.zip) file named same as your roll number.
 Upload it on LMS
 -100 policies for plagiarism

24
DHA SUFFA UNIVERSITY
Department of Computer Science
CS-2001L
Data Structures & Algorithms Lab
Fall 2023
LAB 05
Objective:
Implementation of Circular Linked List using the below operations:
 Traverse
 Insert
 Delete

Theory:

Circular Linked List:


Circular linked list is a linked list where all nodes are connected to form a circle. There is
no NULL at the end. A circular linked list can be a singly circular linked list or doubly
circular linked list.

Singly Circular Linked List:

For creating a node, you can use the following nested class called Node.
Java Code

25
Creating Singly Circular Linked List

Traversal:

26
Insertion:
 Insert at head

 Insert after some node

 Insert at End

27
Deletion:
 Delete Head

 Delete End

 Delete at position

Task: Delete node at specific position

28
DHA SUFFA UNIVERSITY
Department of Computer Science
CS-2001L
Data Structures & Algorithms Lab
Fall 2023
LAB 06

Objective:
 Learn what is Stack
 Learn Stack Operation
 Learn how to implement Stack
o Implementation of stack with Arrays
o Implementation of stack with Linked List.

Stack
A stack is a list of elements in which an element may be inserted or deleted only at one end,
called the top of the stack. This means, in particular, that elements are removed from a stack in
the reverse order of that in which they were inserted into the stack.

Stack Operations
Special terminology is used for two basic operations associated with stacks:
 "Push" is the term used to insert an element into a stack.
 "Pop" is the term used to delete an element from a stack.
The operation of adding (Pushing) an item onto a stack and the operation of removing
(Popping) an item from a stack may be implemented, respectively, by the following procedures,
called PUSH and POP.

In executing the procedure PUSH, one must first test whether there is room in the stack for the
new item; if not, then we have the condition known as overflow. Analogously, in executing the
procedure POP, one must first test whether there is an element in the stack to be deleted; if
not, then we have the condition known as underflow.

LAB # 06
29
Implementation of Stack with Arrays
Create or implement stack in java using array as underlying data structure. We will create stack
class having following methods
 Push method: Push method will be used to insert new element to stack.
 Pop method: Pop method will remove top element of stack.
 Size method: Size method will return current size of stack.
 isEmpty method: isEmpty method will check, whether stack contains any element.
 isFull method: isFull method will check, whether stack has exhausted its capacity.

Creating Stack

1. Stack class

 Stack class composing integer array as underlying data structure.


 Stack class implements push & pop operations to insert & remove element.
 Stack class contains utility methods like isEmpty, isFull & size.

Following functions would be the member functions of stack class.


 push(int element)
 pop()
 isEmpty()
 isFull()
 size()

LAB # 06
30
Pushing an element on a Stack

Popping an element from a Stack

Checking whether stack is empty

Checking whether stack is full

Getting Size of the Stack

LAB # 06
31
2. StackClient class

 StackClient class is client of Stack class.


 StackClient class will create Stack class & push integers to stack.
 StackClient class will traverse the stack & pop all elements from stack.
 We will print size of stack, before & after pop operations.

LAB # 06
32
Implementation of Stack with Linked List
Create or implement stack in java using linked list as underlying data structure. We will create
LinkedList class having nested class Node, used for creating new node and following methods:
 insertFirst method: this method will add/push element on top of the stack.
 deleteFirst method: this method will remove and return the top of the stack.
Above mentioned methods will be used by LinkedListStack class for implementation of Stack
using linked list.

LAB # 06
33
1. Creating Stack with LinkedListStack class

Following functions would be the member functions of LinkedListStack class.


 push(int element)
 pop()
 displayStack()

2. LinkedListStackClient class:

LAB # 06
34
LAB TASK
Perform the following tasks for stack, create separate function for each task.

1. Reverse a string using stack.


2. Reverse a number using stack.
3. Search an element in a stack and return its position (index).
4. Create a peek() method which will return but not remove the top of the stack.

Submission Guidelines
 Write your codes in different notepad (.java) files.
 Place all files in a folder named your roll number e.g. cs162001.
 Compress all files into one (.zip) file named same as your roll number.
 Upload it on LMS
 -100 policies for plagiarism

LAB # 06
35
DHA SUFFA UNIVERSITY
Department of Computer Science
CS-2001L
Data Structures & Algorithms Lab
Fall 2023
LAB 07

Objective:
 Learn what is Queue
 Learn Queue Operations
 Learn how to implement Queue

Queue
A queue is a list of elements with insertions permitted at one end – called the rear, and
deletions permitted from the other end – called the front. This means that the removal of
elements from a queue is possible in the same order in which the insertion of elements is made
into the queue.

Queue data structure possesses the FIFO (first in first out) property. Insert and delete are the
two operations that are provided for insertion of elements and the removal of elements from
the queue, respectively.

Queue Operations
The main operations in a queue are as follows:
 Enqueue (Q, x) – inserts the data element x to the rear-end of the queue
 Dequeue (Q) – deletes the element from the front-end of the queue

Circular Queue
In a normal Queue Data Structure, we can insert elements until queue becomes full. But once if
queue becomes full, we cannot insert the next element until all the elements are deleted from
the queue. This problem can be overcome using circular queue.

Circular Queue is a linear data structure in which the operations are performed based on FIFO
(First In First Out) principle and the last position is connected back to the first position to make
a circle.

LAB # 07
36
Implementing Queue using Arrays

LAB # 07
37
LAB # 07
38
Implementing Queues using LinkedList
LinkedList class

LAB # 07
39
Queue class

QueueClient class

LAB # 07
40
Double Ended Queue
Double Ended Queue is also a Queue data structure in which the insertion and deletion
operations are performed at both the ends (front and rear). That means, we can insert at both
front and rear positions and can delete from both front and rear positions.

LinkedList class

LAB # 07
41
LAB # 07
42
DoubleEndedQueue class

LAB # 07
43
DEQClient class

TASKS
Perform the following tasks create separate function for each task and implement Queue using
LinkedList.
1. Reverse the first K elements of a Queue.
2. Implement a getMinimum() function for Queue.

Submission Guidelines
 Write your codes in different notepad (.java) files with question number e.g. Q1.java
 Place all files in a folder named your roll number e.g. cs162XXX.
 Compress all files into one (.zip) file named same as your roll number.
 Upload it on LMS
 -100 policies for plagiarism

LAB # 07
44
DHA SUFFA UNIVERSITY
Department of Computer Science
CS-2001L
Data Structures & Algorithms Lab
Fall 2023
LAB 08 Binary Tree

Objective
Learning about implementation of following concepts
 Binary Tree
 Binary Tree Traversal
o Pre-Order traversal
o In-Order traversal
o Post-Order traversal

Binary Trees
A binary tree T is defined as a finite set of elements, called nodes, such that
a) T is empty (called the null tree or empty tree), or
b) T contains a distinguished node R, called the root of T, and the remaining nodes of T
form an ordered pair of disjoint binary trees T1 and T2.
c) A tree whose elements have at most 2 children is called a binary tree. Since each
element in a binary tree can have only 2 children, we typically name them the left and
right child.

Example

Binary Tree Representation in Java:


A tree is represented by a reference to the topmost node in tree. If the tree is empty, then
value of root is null.
A Tree node contains following parts.

LAB # 09
45
1. Data
2. Reference to left child
3. Reference to right child

In Java, we can represent a tree node using class Node. Below is an example of a tree node with
an integer data.

Creating Binary Tree

LAB # 09
46
Traversing Binary Tree
Unlike linear data structures (Array, Linked List, Queues, Stacks, etc) which have only one logical
way to traverse them, trees can be traversed in different ways. Following are the generally used
ways for traversing trees.

Depth First Traversals:


(a) Preorder (Root, Left, Right) : 1 2 4 5 3
(b) Inorder (Left, Root, Right) : 4 2 5 1 3
(c) Postorder (Left, Right, Root) : 4 5 2 3 1

(a) Preorder
Algorithm Preorder(tree)
1. Visit the root.
2. Traverse the left subtree, i.e., call Preorder(left-subtree)
3. Traverse the right subtree, i.e., call Preorder(right-subtree)

LAB # 09
47
Figure 1:This method is member of the BinaryTree.java class

(b) Inorder
Algorithm Inorder(tree)
1. Traverse the left subtree, i.e., call Inorder(left-subtree)
2. Visit the root.
3. Traverse the right subtree, i.e., call Inorder(right-subtree)Postorder

Figure 2: This method is member of the BinaryTree.java class

LAB # 09
48
(c) Postorder
Algorithm Postorder(tree)
1. Traverse the left subtree, i.e., call Postorder(left-subtree)
2. Traverse the right subtree, i.e., call Postorder(right-subtree)
3. Visit the root.

Figure 3: This method is member of the BinaryTree.java class

LAB # 09
49
TASKS
Perform the following tasks for binary tree, create separate function for each task.
1. Calculate level of the binary tree.
2. Check whether a given tree is complete tree, full tree or both.
3. Check the children sum property in binary tree, i.e. for every node data values must be
equal to the sum of data values of left and right child.

Submission Guidelines
 Write your codes in different notepad (.java) files with question number e.g. Q1.java
 Place all files in a folder named your roll number e.g. cs162XXX.
 Compress all files into one (.zip) file named same as your roll number.
 Upload it on LMS
 -100 policies for plagiarism

LAB # 09
50
DHA SUFFA UNIVERSITY
Department of Computer Science
CS-2001L
Data Structures & Algorithms Lab
Fall 2023
LAB 09

Objective
Learning about implementation of following concepts of Binary Search Tree.
o Search
o Insertion
o Deletion

Theory
Binary Search Tree

Binary Search Tree is a node-based binary tree data structure which has the following
properties:

 The left subtree of a node contains only nodes with keys lesser than the node’s key.
 The right subtree of a node contains only nodes with keys greater than the node’s key.
 The left and right subtree each must also be a binary search tree.
There must be no duplicate nodes.

The above properties of Binary Search Tree provide an ordering among keys so that the
operations like search, minimum and maximum can be done fast. If there is no ordering, then
we may have to compare every key to search a given key.

Creating a BST:

LAB # 8
51
LAB # 8
52
Main Method:

LAB # 8
53
Searching a key

To search a given key in Binary Search Tree, we first compare it with root, if the key is present
at root, we return root. If key is greater than root’s key, we recur for right subtree of root node.
Otherwise we recur for left subtree.
1. Start from root.
2. Compare the inserting element with root, if less than root, then recurse for left, else recurse
for right.
3. If element to search is found anywhere, return true, else return false.

Insertion of a key

A new key is always inserted at leaf. We start searching a key from root till we hit a leaf
node. Once a leaf node is found, the new node is added as a child of the leaf node.

LAB # 8
54
Deletion:

We have discussed BST search and insert operations. Further, delete operation is discussed.
When we delete a node, there possibilities arise.
1) Node to be deleted is leaf: Simply remove from the tree.
2) Node to be deleted has only one child: Copy the child to the node and delete the child
3) Node to be deleted has two children: Find inorder successor of the node. Copy contents
of the inorder successor to the node and delete the inorder successor. Note that inorder
predecessor can also be used.

LAB # 8
55
LAB TASKS
1) Design a binary expression tree representation of the following arithmetic expression.
((5+2)*(2-1))/(2+9)
Create a function for the traversal of the expression tree.

2) Convert a given sorted array into Binary Search Tree.

3) Convert a Binary tree into Binary Search Tree.

Submission Guidelines
 Write your codes in different notepad (.java) files.
 Place all files in a folder named your roll number e.g. cs162001.
 Compress all files into one (.zip) file named same as your roll number.
 Upload it on LMS
 -100 policies for plagiarism

LAB # 8
56
DHA SUFFA UNIVERSITY
Department of Computer Science
CS-2001L
Data Structures & Algorithms Lab
Fall 2023
LAB 10

Objective:
Learning about implementation of following concepts of AVL Trees.

• Insertion
• Deletion
AVL Trees:
An AVL tree is another balanced binary search tree. Named after their inventors, Adelson-Velskii
and Landis, they were the first dynamically balanced trees to be proposed. Like red-black trees,
they are not perfectly balanced, but pairs of sub-trees differ in height by at most 1, maintaining
an O(logn) search time. Addition and deletion operations also take O(logn) time.

Definition of an AVL tree


An AVL tree is a binary search tree which has the following properties:

1. The sub-trees of every node differ in height by at most one.


2. Every sub-tree is an AVL tree.

Insertion:
To make sure that the given tree remains AVL after every insertion, we must augment the
standard BST insert operation to perform some re-balancing. Following are two basic operations
that can be performed to re-balance a BST without violating the BST property (keys(left) <
key(root) < keys(right)).

1) Left Rotation

2) Right Rotation.

T1, T2 and T3 are subtrees of the tree rooted with y (on left side)
or x (on right side)

57
y x

/ \ Right Rotation / \

x T3 – – – – – – – > T1 y

/ \ < - - - - - - - / \

T1 T2 Left Rotation T2 T3

Keys in both of the above trees follow the following order


keys(T1) < key(x) < keys(T2) < key(y) < keys(T3)
So BST property is not violated anywhere.

Steps to follow for insertion


Let the newly inserted node be w

1) Perform standard BST insert for w.


2) Starting from w, travel up and find the first unbalanced node. Let z be the first unbalanced
node, y be the child of z that comes on the path from w to z and x be the grandchild of z that
comes on the path from w to z.
3) Re-balance the tree by performing appropriate rotations on the subtree rooted with z. There
can be 4 possible cases that needs to be handled as x, y and z can be arranged in 4 ways.
Following are the possible 4 arrangements:
a) y is left child of z and x is left child of y (Left Left Case)
b) y is left child of z and x is right child of y (Left Right Case)
c) y is right child of z and x is right child of y (Right Right Case)
d) y is right child of z and x is left child of y (Right Left Case)

Following are the operations to be performed in above mentioned 4 cases. In all of the cases,
we only need to re-balance the subtree rooted with z and the complete tree becomes balanced
as the height of subtree (After appropriate rotations) rooted with z becomes same as it was
before insertion.

a) Left Left Case


T1, T2, T3 and T4 are subtrees.
z y

/ \ / \
y T4 Right Rotate (z) x z

/ \ - --------------- > / \ / \

x T3 T1 T2 T3 T4

/ \
T1 T2

58
b) Left Right Case
z z x

/ \ / \ / \

y T4 Left Rotate (y) x T4 Right Rotate(z) y z

/ \ - --------------- > / \ - - - - - - - -> / \ / \

T1 x y T3 T1 T2 T3 T4

/ \ / \

T2 T3 T1 T2

c) Right Right Case


z y
/ \ / \

T1 y Left Rotate(z) z x

/ \ ----------------- > / \ / \

T2 x T1 T2 T3 T4

/ \
T3 T4

d) Right Left Case


z z x
/ \ / \ / \

T1 y Right Rotate (y) T1 x Left Rotate(z) z y

/ \ ------------------ > / \ - - - - - - - -> / \ / \

x T4 T2 y T1 T2 T3 T4
/ \ / \

T2 T3 T3 T4

59
Implementation in Java

60
61
62
63
Deletion:
Steps to follow for deletion

To make sure that the given tree remains AVL after every deletion, we must augment the
standard BST delete operation to perform some re-balancing. Following are two basic
operations that can be performed to re-balance a BST without violating the BST property
(keys(left) < key(root) < keys(right)).

1) Left Rotation

2) Right Rotation

T1, T2 and T3 are subtrees of the tree rooted with y (on left side)
or x (on right side)

y x

/ \ Right Rotation / \

x T3 – – – – – – – > T1 y

/ \ < - - - - - - - / \

T1 T2 Left Rotation T2 T3

Keys in both of the above trees follow the following order


keys(T1) < key(x) < keys(T2) < key(y) < keys(T3)

So BST property is not violated anywhere.

Let w be the node to be deleted

1) Perform standard BST delete for w.


2) Starting from w, travel up and find the first unbalanced node. Let z be the first unbalanced
node, y be the larger height child of z, and x be the larger height child of y. Note that the
definitions of x and y are different from insertion here.
3) Re-balance the tree by performing appropriate rotations on the subtree rooted with z. There
can be 4 possible cases that needs to be handled as x, y and z can be arranged in 4 ways.
Following are the possible 4 arrangements:
a) y is left child of z and x is left child of y (Left Left Case)
b) y is left child of z and x is right child of y (Left Right Case)
c) y is right child of z and x is right child of y (Right Right Case)
d) y is right child of z and x is left child of y (Right Left Case)

Like insertion, following are the operations to be performed in above mentioned 4 cases. Note
that, unlike insertion, fixing the node z won’t fix the complete AVL tree. After fixing z, we may
have to fix ancestors of z as well.

64
a) Left Left Case
T1, T2, T3 and T4 are subtrees.
z y

/ \ / \

y T4 Right Rotate (z) x z

/ \ - --------------- > / \ / \

x T3 T1 T2 T3 T4

/ \
T1 T2

b) Left Right Case


z z x

/ \ / \ / \

y T4 Left Rotate (y) x T4 Right Rotate(z) y z


/ \ - --------------- > / \ - - - - - - - -> / \ / \

T1 x y T3 T1 T2 T3 T4

/ \ / \

T2 T3 T1 T2

c) Right Right Case


z y

/ \ / \

T1 y Left Rotate(z) z x

/ \ ----------------- > / \ / \

T2 x T1 T2 T3 T4

/ \
T3 T4

d) Right Left Case


z z x

/ \ / \ / \

T1 y Right Rotate (y) T1 x Left Rotate(z) z x

/ \ ------------------ > / \ - - - - - - - -> / \ / \

x T4 T2 y T1 T2 T3 T4

/ \ / \
T2 T3 T3 T4

65
Lab Task

Perform deletion in AVL tree, cover all the cases discussed above for deletion.

Submission Guidelines

 Write your codes in different notepad (.java) files with question number e.g. Q1.java
 Place all files in a folder named your roll number e.g. cs162XXX.
 Compress all files into one (.zip) file named same as your roll number.
 Upload it on LMS
 -100 policies for plagiarism

66
DHA SUFFA UNIVERSITY
Department of Computer Science
CS-2001L
Data Structures & Algorithms Lab
Fall 2023
LAB 11 Graphs

Objective:
Learning about implementation of graphs using following approaches:

• Depth First Search


• Breadth First Search
Graphs:
A graph is a pictorial representation of a set of objects where some pairs of objects are
connected by links. The interconnected objects are represented by points termed as vertices,
and the links that connect the vertices are called edges.
Formally, a graph is a pair of sets (V, E), where V is the set of vertices and E is the set of edges,
connecting the pairs of vertices. Take a look at the following graph

In the above graph,

V = {a, b, c, d, e}

E = {ab, ac, bd, cd, de}

Following are basic primary operations of a Graph −

 Add Vertex − Adds a vertex to the graph.

 Add Edge − Adds an edge between the two vertices of the graph.

 Display Vertex − Displays a vertex of the graph

67
Depth First Search(dfs):
Depth First Search (DFS) algorithm traverses a graph in a depthward motion and uses a stack to
remember to get the next vertex to start a search, when a dead end occurs in any iteration

For implementing Depth-First Traversal for a graph perform following steps

1. Create vertex class and define above methods in that

2. Create a stack class

 LinkedList.java

 LinkedListStack.java (Stack implementation using linked list)

68
69
70
3. create Graph class and define createVertex() for adding vertexes in graphs,createEdge()
method for creating connections between vertexes of graph.

Rules for Depth first search (dfs) are as follows


 Rule 1 − Visit the adjacent unvisited vertex. Mark it as visited. Display it. Push it in a
stack.

 Rule 2 − If no adjacent vertex is found, pop up a vertex from the stack. (It will pop up all
the vertices from the stack, which do not have adjacent vertices.)

 Rule 3 − Repeat Rule 1 and Rule 2 until the stack is empty.

71
4. call function in main method

72
Breadth First Search(bfs):
Breadth First Search (BFS) algorithm traverses a graph in a breadthward motion and uses a
queue to remember to get the next vertex to start a search, when a dead end occurs in any
iteration.

As in the example given above, BFS algorithm traverses from A to B to E to F first then to C and
G lastly to D. It employs the following rules.

 Rule 1 − Visit the adjacent unvisited vertex. Mark it as visited. Display it. Insert it in a
queue.

 Rule 2 − If no adjacent vertex is found, remove the first vertex from the queue.

 Rule 3 − Repeat Rule 1 and Rule 2 until the queue is empty.

For implementing Breadth First search traversal for a graph perform following steps

1. Create vertex and Graph class as given above.


2. Create a Queue class (implemented using linked list, which has been created previously)
Note: We have called this Queue class as Queue_2.java

73
74
3. Create printGraphBF() which will traverse the graph breadth wise.

4. Calling printfGraphBF() through main method.

75
LAB TASK

Perform the following tasks for Graph, create separate function for each task.

1. Calculate degree of each node for an undirected graph.


2. Perform Breadth first traversal and depth first traversal for Directed graph.

Submission Guidelines

 Write your codes in different notepad (.java) files.


 Place all files in a folder named your roll number e.g. cs162001.
 Compress all files into one (.zip) file named same as your roll number.
 Upload it on LMS
 -100 policies for plagiarism

76
DHA SUFFA UNIVERSITY
Department of Computer Science
CS-2001L
Data Structures & Algorithms Lab
Fall 2023
LAB 12 Selection,Merge & Quick Sort

Objective:
Learning about implementation of following sorting algorithm:

• Merge Sort
• Quick Sort
• Merge Sort

Merge Sort:
Merge sort is a sorting technique based on divide and conquer technique. With worst-case time
complexity being Ο(n log n), it is one of the most respected algorithms.

Merge sort first divides the array into equal halves and then combines them in a sorted manner.

Algorithm

Merge sort keeps on dividing the list into equal halves until it can no more be divided. By
definition, if it is only one element in the list, it is sorted. Then, merge sort combines the smaller
sorted lists keeping the new list sorted too.

I. If there is only one element in the list, it is already sorted, return.


II. Divide the list recursively into two halves until it can no more be divided.
III. Merge the smaller lists into new list in sorted order.

77
78
Java Code for MergeSort

79
Quick Sort:
Quick sort is a highly efficient sorting algorithm and is based on partitioning of array of data into
smaller arrays. A large array is partitioned into two arrays one of which holds values smaller
than the specified value, say pivot, based on which the partition is made and another array
holds values greater than the pivot value.

Quick sort partitions an array and then calls itself recursively twice to sort the two resulting
subarrays. This algorithm is quite efficient for large-sized data sets as its average and worst case
complexity are of Ο(n2), where n is the number of items.

Using pivot algorithm recursively, we end up with smaller possible partitions. Each partition is
then processed for quick sort. We define recursive algorithm for quicksort as follows:

Step 1 − Make the right-most index value pivot


Step 2 − partition the array using pivot value
Step 3 − quicksort left partition recursively
Step 4 − quicksort right partition recursively

80
The pivot value divides the list into two parts. And recursively, we find the pivot for each sub-
lists until all lists contains only one element.

Java Code

81
Selection Sort:
The selection sort algorithm sorts an array by repeatedly finding the minimum element
(considering ascending order) from unsorted part and putting it at the beginning. The algorithm
maintains two subarrays in a given array.
1) The subarray which is already sorted.
2) Remaining subarray which is unsorted.

In every iteration of selection sort, the minimum element (considering ascending order) from
the unsorted subarray is picked and moved to the sorted subarray.
Following example explains the above steps:

arr[] = 20 37 12

// Find the minimum element in arr[0...2]

// and place it at beginning

82
12 37 20

// Find the minimum element in arr[1...4]


// and place it at beginning of arr[1...4]
12 20 37

83
DHA SUFFA UNIVERSITY
Department of Computer Science
CS 2001L- Data Structures &Algorithms
Fall 2023
LAB 13- Bubble Sort

Objective:
Learning about implementation of following sorting algorithm:

• Bubble Sort

Bubble Sort Algorithm

Bubble Sort is an elementary sorting algorithm, which works by repeatedly exchanging adjacent elements, if
necessary. When no exchanges are required, the file is sorted.

We assume list is an array of n elements. We further assume that swap function swaps the values of the
given array elements.

Step 1 − Check if the first element in the input array is greater than the next element in the array.

Step 2 − If it is greater, swap the two elements; otherwise move the pointer forward in the array.

Step 3 − Repeat Step 2 until we reach the end of the array.

Step 4 − Check if the elements are sorted; if not, repeat the same process (Step 1 to Step 3) from the last
element of the array to the first.

Step 5 − The final output achieved is the sorted array.

Algorithm: Sequential-Bubble-Sort (A)


fori ← 1 to length [A] do
for j ← length [A] down-to i +1 do
if A[A] < A[j-1] then
Exchange A[j] ⟷ A[j-1]

84
Pseudocode
We observe in algorithm that Bubble Sort compares each pair of array element unless the whole array is
completely sorted in an ascending order. This may cause a few complexity issues like what if the array needs
no more swapping as all the elements are already ascending.

To ease-out the issue, we use one flag variable swapped which will help us see if any swap has happened or
not. If no swap has occurred, i.e. the array requires no more processing to be sorted, it will come out of the
loop.

Pseudocode of bubble sort algorithm can be written as follows −

voidbubbleSort(int numbers[], intarray_size){


inti, j, temp;
for (i = (array_size - 1); i>= 0; i--)
for (j = 1; j <= i; j++)
if (numbers[j-1] > numbers[j]){
temp = numbers[j-1];
numbers[j-1] = numbers[j];
numbers[j] = temp;
}
}

Analysis
Here, the number of comparisons are

1 + 2 + 3 + ... + (n - 1) = n(n - 1)/2 = O(n2)

Clearly, the graph shows the n2 nature of the bubble sort.

In this algorithm, the number of comparison is irrespective of the data set, i.e. whether the provided input
elements are in sorted order or in reverse order or at random.

Memory Requirement
From the algorithm stated above, it is clear that bubble sort does not require extra memory.

85
Example
We take an unsorted array for our example. Bubble sort takes Ο(n2) time so we're keeping it short and
precise.

Bubble sort starts with very first two elements, comparing them to check which one is greater.

In this case, value 33 is greater than 14, so it is already in sorted locations. Next, we compare 33 with 27.

We find that 27 is smaller than 33 and these two values must be swapped.

Next we compare 33 and 35. We find that both are in already sorted positions.

Then we move to the next two values, 35 and 10.


86
We know then that 10 is smaller 35. Hence they are not sorted. We swap these values. We find that we have
reached the end of the array. After one iteration, the array should look like this −

To be precise, we are now showing how an array should look like after each iteration. After the second
iteration, it should look like this −

Notice that after each iteration, at least one value moves at the end.

And when there's no swap required, bubble sort learns that an array is completely sorted.

87
Now we should look into some practical aspects of bubble sort.

Implementation

One more issue we did not address in our original algorithm and its improvised pseudocode, is that, after
every iteration the highest values settles down at the end of the array. Hence, the next iteration need not
include already sorted elements. For this purpose, in our implementation, we restrict the inner loop to avoid
already sorted values.

import java.io.*;
import java.util.*;
public class BubbleSort {
public static void main(String args[]) {
int n = 5;
int[] arr = {67, 44, 82, 17, 20}; //initialize an
array
System.out.print("Array before Sorting: ");
for(int i = 0; i<n; i++)
System.out.print(arr[i] + " ");
System.out.println();
for(int i = 0; i<n; i++) {
int swaps = 0; //flag to detect any swap is there
or not
for(int j = 0; j<n-i-1; j++) {
if(arr[j] > arr[j+1]) { //when the current item
is bigger than next
int temp;
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
swaps = 1; //set swap flag
}
}
if(swaps == 0)
break;
}
System.out.print("Array After Sorting: ");
for(int i = 0; i<n; i++)
System.out.print(arr[i] + " ");
System.out.println();
}
}

88
Output
Array before Sorting: 67 44 82 17 20
Array After Sorting: 17 20 44 67 82

89
DHA SUFFA UNIVERSITY
Department of Computer Science
CS-2001L Data Structures & Algorithms Lab
Fall 2023
LAB 14 Hash Table Data structure

Objective:
Learning about implementation of following

• Hash table

Hash Table is a data structure which stores data in an associative manner. In a hash table, data is stored in an
array format, where each data value has its own unique index value. Access of data becomes very fast if we
know the index of the desired data.

Thus, it becomes a data structure in which insertion and search operations are very fast irrespective of the size
of the data. Hash Table uses an array as a storage medium and uses hash technique to generate an index where
an element is to be inserted or is to be located from.

Hashing

Hashing is a technique to convert a range of key values into a range of indexes of an array. We're going to use
modulo operator to get a range of key values. Consider an example of hash table of size 20, and the following
items are to be stored. Item are in the (key,value) format.

90
 (1,20)
 (2,70)
 (42,80)
 (4,25)
 (12,44)
 (14,32)
 (17,11)
 (13,78)
 (37,98)

Sr.No. Key Hash Array Index

1 1 1 % 20 = 1 1

2 2 2 % 20 = 2 2

3 42 42 % 20 = 2 2

4 4 4 % 20 = 4 4

5 12 12 % 20 = 12 12

6 14 14 % 20 = 14 14

7 17 17 % 20 = 17 17

8 13 13 % 20 = 13 13

9 37 37 % 20 = 17 17

Basic Operations

Following are the basic primary operations of a hash table.

 Search − Searches an element in a hash table.


 Insert − Inserts an element in a hash table.
 Delete − Deletes an element from a hash table.
DataItem

Define a data item having some data and key, based on which the search is to be conducted in a hash table.

struct DataItem {
int data;
int key;
};

91
Hash Method
Define a hashing method to compute the hash code of the key of the data item.

int hashCode(int key){


return key % SIZE;
}

Search Operation

Whenever an element is to be searched, compute the hash code of the key passed and locate the element using
that hash code as index in the array. Use linear probing to get the element ahead if the element is not found at
the computed hash code.

struct DataItem *search(int key) {


//get the hash
int hashIndex = hashCode(key);

//move in array until an empty


while(hashArray[hashIndex] != NULL) {

if(hashArray[hashIndex]->key == key)
return hashArray[hashIndex];

//go to next cell


++hashIndex;

//wrap around the table


hashIndex %= SIZE;
}

return NULL;
}

92
Example
Following are the implementations of this operation in various programming language

import java.util.HashMap;
public class Main {
static final int SIZE = 10; // Define the size of the hash table
static class DataItem {
int key;
}
static HashMap<Integer, DataItem> hashMap = new HashMap<>(); //
Define the hash table as a HashMap

static int hashCode(int key) {


// Return a hash value based on the key
return key % SIZE;
}
static DataItem search(int key) {
// get the hash
int hashIndex = hashCode(key);

// move in map until an empty slot is found or the key is found


while (hashMap.get(hashIndex) != null) {
// If the key is found, return the corresponding DataItem
if (hashMap.get(hashIndex).key == key)
return hashMap.get(hashIndex);

// go to the next cell


++hashIndex;

// wrap around the table


hashIndex %= SIZE;
}

// If the key is not found, return null


return null;
}
public static void main(String[] args) {
// Initializing the hash table with some sample DataItems

DataItem item2 = new DataItem();


item2.key = 25; // Assuming the key is 25

DataItem item3 = new DataItem();


item3.key = 64; // Assuming the key is 64
DataItem item4 = new DataItem();
item4.key = 22; // Assuming the key is 22
// Calculate the hash index for each item and place them in the
hash table

int hashIndex2 = hashCode(item2.key); 93


hashMap.put(hashIndex2, item2);

int hashIndex3 = hashCode(item3.key);


hashMap.put(hashIndex3, item3);

int hashIndex4 = hashCode(item4.key);


hashMap.put(hashIndex4, item4);

// Call the search function to test it


int keyToSearch = 64; // The key to search for in the hash table
DataItem result = search(keyToSearch);
System.out.print("The element to be searched: " + keyToSearch);
if (result != null) {
System.out.println("\nElement found");
} else {
System.out.println("\nElement not found");
}
}
}

Output
The element to be searched: 64
Element found

Insert Operation

Whenever an element is to be inserted, compute the hash code of the key passed and locate the index using
that hash code as an index in the array. Use linear probing for empty location, if an element is found at the
computed hash code.

import java.util.Arrays;
public class Main {
static final int SIZE = 4; // Define the size of the hash table
static class DataItem {
int key;
}
static DataItem[] hashArray = new DataItem[SIZE]; // Define the
hash table as an array of DataItem pointers
static int hashCode(int key) {
// Return a hash value based on the key
return key % SIZE;
}
static void insert(int key) {
// Create a new DataItem
DataItem newItem = new DataItem();
newItem.key = key;
// Initialize other data members if needed

// Calculate the hash index for the key


int hashIndex = hashCode(key);
94
// Handle collisions (linear probing)
while (hashArray[hashIndex] != null) {
// Move to the next cell
hashIndex++;
// Wrap around the table if needed
hashIndex %= SIZE;
}
// Insert the new DataItem at the calculated index
hashArray[hashIndex] = newItem;
}
public static void main(String[] args) {
// Call the insert function with different keys to populate the
hash table
insert(42); // Insert an item with key 42
insert(25); // Insert an item with key 25
insert(64); // Insert an item with key 64
insert(22); // Insert an item with key 22
// Output the populated hash table
for (int i = 0; i < SIZE; i++) {
if (hashArray[i] != null) {
System.out.println("Index " + i + ": Key " +
hashArray[i].key);
} else {
System.out.println("Index " + i + ": Empty");
}
}
}
}

Output
Index 0: Key 64
Index 1: Key 25
Index 2: Key 42
Index 3: Key 22

95
Delete Operation

Whenever an element is to be deleted, compute the hash code of the key passed and locate the index using that
hash code as an index in the array. Use linear probing to get the element ahead if an element is not found at
the computed hash code. When found, store a dummy item there to keep the performance of the hash table
intact.

public class Main {


static final int SIZE = 5; // Define the size of the hash table
static class DataItem {
int key;
DataItem(int key) {
this.key = key;
}
}
static DataItem[] hashArray = new DataItem[SIZE]; // Define the hash
table as an array of DataItem objects
static int hashCode(int key) {
// Implement your hash function here
// Return a hash value based on the key
return key % SIZE; // A simple hash function using modulo operator
}
static void insert(int key) {
// Calculate the hash index for the key
int hashIndex = hashCode(key);
// Handle collisions (linear probing)
while (hashArray[hashIndex] != null) {
// Move to the next cell
hashIndex = (hashIndex + 1) % SIZE;
}

// Insert the new DataItem at the calculated index


hashArray[hashIndex] = new DataItem(key);

// Print the inserted item's key and hash index


System.out.println("Inserted key " + key + " at index " + hashIndex);
}
static void delete(int key) {
// Find the item in the hash table
int hashIndex = hashCode(key);
while (hashArray[hashIndex] != null) {
if (hashArray[hashIndex].key == key) {
// Mark the item as deleted (optional: free memory)
hashArray[hashIndex] = null;

// Print the deleted item's key and hash index


return;
}
// Move to the next cell
hashIndex = (hashIndex + 1) % SIZE;
}
// If the key is not found, print a message
System.out.println("Item with key " + key + " not found.");
}
public static void main(String[] args) {
96
// Call the insert function with different keys to populate the hash
table
System.out.println("Hash Table Contents before deletion: ");
insert(1); // Insert an item with key 1
insert(2); // Insert an item with key 2
insert(3); // Insert an item with key 3
insert(4); // Insert an item with key 4
int ele1 = 2;
int ele2 = 4;
System.out.print("The keys to be deleted: " + ele1 + " and " + ele2);
delete(ele1); // Delete an item with key 2
delete(ele2); // Delete an item with key 4
// Print the hash table's contents after delete operations
System.out.println("\nHash Table Contents after deletion:");
for (int i = 1; i < SIZE; i++) {
if (hashArray[i] != null) {
System.out.println("Index " + i + ": Key " + hashArray[i].key);
} else {
System.out.println("Index " + i + ": Empty");
}
}
}
}

Output
Hash Table Contents before deletion:
Inserted key 1 at index 1
Inserted key 2 at index 2
Inserted key 3 at index 3
Inserted key 4 at index 4
The keys to be deleted: 2 and 4
Hash Table Contents after deletion:
Index 1: Key 1
Index 2: Empty
Index 3: Key 3
Index 4: Empty

97
Complete implementation

Following are the complete implementations of the above operations in various programming languages −

public class HashTableExample {


static final int SIZE = 20;
static class DataItem {
int data;
int key;
DataItem(int data, int key) {
this.data = data;
this.key = key;
}
}
static DataItem[] hashArray = new DataItem[SIZE];
static DataItem dummyItem = new DataItem(-1, -1);
static DataItem item;
static int hashCode(int key) {
return key % SIZE;
}
static DataItem search(int key) {
int hashIndex = hashCode(key);

while (hashArray[hashIndex] != null) {


if (hashArray[hashIndex].key == key)
return hashArray[hashIndex];

hashIndex = (hashIndex + 1) % SIZE;


}
return null;
}
static void insert(int key, int data) {
DataItem item = new DataItem(data, key);
int hashIndex = hashCode(key);

while (hashArray[hashIndex] != null && hashArray[hashIndex].key != -


1) {
hashIndex = (hashIndex + 1) % SIZE;
}
hashArray[hashIndex] = item;
}
static DataItem deleteItem(DataItem item) {
int key = item.key;
int hashIndex = hashCode(key);
while (hashArray[hashIndex] != null) {
if (hashArray[hashIndex].key == key) {
DataItem temp = hashArray[hashIndex];
hashArray[hashIndex] = dummyItem;
return temp;
}

hashIndex = (hashIndex + 1) % SIZE;


}
return null;
}
98
static void display() {
for (int i = 0; i < SIZE; i++) {
if (hashArray[i] != null)
System.out.print(" (" + hashArray[i].key + "," +
hashArray[i].data + ")");
}
System.out.println();
}
public static void main(String[] args) {
insert(1, 20);
insert(2, 70);
insert(42, 80);
insert(4, 25);
insert(12, 44);
insert(14, 32);
insert(17, 11);
insert(13, 78);
insert(37, 97);
System.out.print("Insertion done");
System.out.print("\nContents of Hash Table:");
display();
int ele = 37;
System.out.print("The element to be searched: " + ele);
item = search(37);

if (item != null) {
System.out.println("\nElement found: " + item.key);
} else {
System.out.println("\nElement not found");
}
deleteItem(item);
System.out.print("Hash Table contents after deletion:");
display();
}
}

Output
Insertion done
Contents of Hash Table: (1,20) (2,70) (42,80) (4,25) (12,44) (13,78) (14,32) (17,11) (37,97)
The element to be searched: 37
Element found: 37
Hash Table contents after deletion: (1,20) (2,70) (42,80) (4,25) (12,44) (13,78) (14,32)

99

You might also like