DSA MasterLabManual Fall2024
DSA MasterLabManual Fall2024
Master Manual
CS-2001L
Fall 2024
Index
Approval from
S.No Title
teacher
6 Implementation of Stack
7 Implementation of Queue
11 Implementation of Graphs
14 Implementation of HashTable
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.
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.
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:
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.
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
5
Loops
o For Loop
o For-each or Enhanced For Loop
o While loop
o Do while 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
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.
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
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
LAB # 02
12
LAB TASKS
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.
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
15
Traversing a linked list
16
Java Code:
Java Code:
17
Task:
Write a Java program to implement insertion a node at the end of the 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
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
Task:
Write a Java program to implement insertion of a node at the end of the doubly linked
list.
22
Java Code
Task:
Write a Java program to implement insertion of a node before specific node.
insertBefore(Node next_node,int new_data)
Java Code
Task:
Write a Java program to implement deletion of the last node in doubly linked 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:
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 at End
27
Deletion:
Delete Head
Delete End
Delete at 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
LAB # 06
30
Pushing an element on a Stack
LAB # 06
31
2. StackClient class
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
2. LinkedListStackClient class:
LAB # 06
34
LAB TASK
Perform the following tasks for stack, create separate function for each task.
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
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.
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.
(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
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.
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.
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.
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
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.
/ \ / \
y T4 Right Rotate (z) x z
/ \ - --------------- > / \ / \
x T3 T1 T2 T3 T4
/ \
T1 T2
58
b) Left Right Case
z z x
/ \ / \ / \
T1 x y T3 T1 T2 T3 T4
/ \ / \
T2 T3 T1 T2
T1 y Left Rotate(z) z x
/ \ ----------------- > / \ / \
T2 x T1 T2 T3 T4
/ \
T3 T4
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
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
/ \ / \
/ \ - --------------- > / \ / \
x T3 T1 T2 T3 T4
/ \
T1 T2
/ \ / \ / \
T1 x y T3 T1 T2 T3 T4
/ \ / \
T2 T3 T1 T2
/ \ / \
T1 y Left Rotate(z) z x
/ \ ----------------- > / \ / \
T2 x T1 T2 T3 T4
/ \
T3 T4
/ \ / \ / \
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:
V = {a, b, c, d, e}
Add Edge − Adds an edge between the two vertices 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
LinkedList.java
68
69
70
3. create Graph class and define createVertex() for adding vertexes in graphs,createEdge()
method for creating connections between vertexes of graph.
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.)
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.
For implementing Breadth First search traversal for a graph perform following steps
73
74
3. Create printGraphBF() which will traverse the graph breadth wise.
75
LAB TASK
Perform the following tasks for Graph, create separate function for each task.
Submission Guidelines
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.
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:
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
82
12 37 20
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 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 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.
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.
Analysis
Here, the number of comparisons are
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.
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)
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
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.
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.
if(hashArray[hashIndex]->key == key)
return hashArray[hashIndex];
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
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
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.
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 −
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