Ds Study Material (Java)
Ds Study Material (Java)
Concept of Abstract Data Types (ADTs)- Data Types, Data Structures, Primitive and Non-primitive Data
Structures, Linear and Non-linear Data Structures.
Linear Lists– ADT, Array and Linked representations, Pointers.
Arrays: One Dimensional-Two Dimensional-Multi Dimensional-Operations-Sparse Matrices.
Linked Lists: Single Linked List, Double Linked List, Circular Linked List , applications
UNIT II
Stacks: Definition, ADT, Array and Linked representations, Implementations and Applications
Queues: Definition, ADT, Array and Linked representations, Circular Queues, Dequeues, Priority Queues,
Implementations and Applications.
UNIT III
Trees:
Binary Tree: Definition, Properties, ADT, Array and Linked representations, Implementations and
Applications.
Binary Search Trees (BST) – Definition, ADT, Operations and Implementations, BST Applications. Threaded
Binary Trees, Heap trees.
UNIT IV
Graphs – Graph and its Representation, Graph Traversals, Connected Components, Basic Searching
Techniques, Minimal Spanning Trees
UNIT- V
Sorting and Searching: Selection, Insertion, Bubble, Merge, Quick, Heap sort, Sequential and Binary
Searching.
1|Page
UNIT-1
Abstract Data Type (ADT):
Abstract Data Type is an organized collection of information and set of operations used to
manage that information.
1. An ADT is considered as Abstract because the operations performed on it are separated from
implementation.
2. Most Data Structure ADT‟s can be implemented either by using Arrays or by using Linked List.
3. An ADT can be represented as follows.
An abstract data-type is an organized collection of information and a set of operations used to manage
that information.
It is a logical description of how we view the data and how the operations will be implemented. The
abstract data type is referred as ADT. It is represented by an interface.
Below diagram shows that, what an abstract data type is and how it operates. The user interacts with the
interface using the operations that have been specified by the abstract data type.
When an application requires a special kind of data which is not available as built-in datatype. Then it is
the programmer burden to implement own kind of data type. For example, if we want to process data of the
form dd/mm/yyyy, then the programmer perform various operations like adding few days to date to obtain
another date, to find days should be defined accoedingly.
Data Types:
1. A data type is a set of data values having predefined characteristics like range and size.
2. Examples of data types would be integer, float, char etc.
3. Generally, all programming languages have limited number of such data types.
4. The range of values that can be stored in each of these data types is defined by the language and
computer hardware.
5. The basic data types also known as primitive data types.
6. Data types can be divided into two types. Those are
a. Scalar Data types
b. Structured Data types
2|Page
SCALAR DATA TYPES:
A scalar or simple data types consists of a collection of ordered values and set of operations that can be
performed on those values. The C, C++ and Java programming language‟s primitive data types referred as
scalar data types.
A scalar variable can hold only one piece of data at a time. int, char, float etc.. are referred as scalar data
types.
DATA STRUCTURE:
The specialized format of organizing and storing data in memory is known as Data structure. Data
structures are of two types.
1. Primitive data structures
2. Non-primitive data structures
PRIMITIVE DATA STRUCTURES: These are system defined data structures. These data structures includes
integer, real, character and boolean.
NON-PRIMITIVE DATA STRUCTURES: These are user defined data structures. These are further divided
into two categories.
1. Linear Data Structures
2. Non-Linear Data Structures
ARRAY:
An array is a collection of homogeneous data elements which can store continuous memory locations
and having the same name. Each element in the array will be accessed by using subscript or index.
LINKED LIST:
A linked list is a collection of “nodes” which maintain a linear order with links. Here each node contains
two parts, data part and reference part.
STACK:
A stack is a linear data structure in which elements are processed in LIFO (Last In First Out) manner
which means the element which is inserted last will be the first one to remove. Insertions and deletions can be
performed at only one end called “TOP”.
QUEUE:
A queue is a linear data structure which follows FIFO(First In First Out) mechanism, which means the
element which was inserted first into the queue will be the first one to remove. The insertion in queue is done at
one end and deletions are performed at another end.
TREE:
A Tree is a non-linear data structure used to represent one to many relationships with data items. A tree
is used to represent hierarchical relationships.
“A tree T(n), is an unordered collection of data items distributed non-linearly such as
GRAPH:
A Graph is a non linear data structure and is denoted by G(V,E), where V is set of vertices and E is set
of edges. A graph is used to represent many to many relationships with the data items. A vertices us nothing but
data element and the edge is nothing but a connection between two vertices.
Array:
An array is a collection of Homogeneous data elements which can store in continuous memory locations
and having the same name.
1. An array is called homogeneous collection because it can store only similar data items.
2. Each item in the array will be accessed by an index or subscript.
3. Based on the number of subscripts the arrays are classified into the following categories.
a. One dimensional array
b. Two dimensional array
c. Multi dimensional array
5|Page
Creation:
Every variable must be declared before it is using since the array is also a variable it must be declared like other
variables.
Syntax:
data-type array-name [ ];
data-type [ ] araay-name;
Example: int a [ ];
int [ ] a;
In the above example „a‟ is the name of the array it must be any valid identifier.
Syntax:
Array-name = new data-type [ size ];
Example:
a = new int [ 10 ];
In the above example, a has been given size of 10. So it can hold 10 integer values. We can also
combine the declaration and creating memory into a single statement as follows.
a[0] = 10
a[1] = 20
a[2] = 30
import java.lang.*;
import java.util.*;
class ArrayDemo
{
6|Page
public static void main(String args[])
{
Scanner s=new Scanner(System.in);
System.out.println("How many elements you want to read:");
int n=s.nextInt();
int a[]=new int[n];
System.out.println("Enter "+n+" elements:");
for(int i=0;i<n;i++)
a[i]=s.nextInt();
System.out.println("Array elements are:");
for(int i=0;i<a.length;i++)
System.out.println(a[i]);
}
}
Example:
int a[ ][ ];
int[ ][ ] a;
import java.lang.*;
import java.util.*;
class MatrixMultiplication
{
public static void main(String args[])
7|Page
{
Scanner s=new Scanner(System.in);
System.out.println("First matrix dimensions:");
int r1=s.nextInt();
int c1=s.nextInt();
System.out.println("Second matrix dimensions:");
int r2=s.nextInt();
int c2=s.nextInt();
if(c1!=r2)
{
System.out.println("Multiplication Not Possible");
}
else
{
int a[][]=new int[r1][c1];
int b[][]=new int[r2][c2];
int c[][]=new int[r1][c2];
System.out.println("Enter first matrix elements:");
for(int i=0;i<r1;i++)
for(int j=0;j<c1;j++)
a[i][j]=s.nextInt();
System.out.println("Enter second matrix elements:");
for(int i=0;i<r2;i++)
for(int j=0;j<c2;j++)
b[i][j]=s.nextInt();
for(int i=0;i<r1;i++)
{
for(int j=0;j<c2;j++)
{
c[i][j]=0;
for(int k=0;k<c1;k++)
{
c[i][j]+=a[i][k]*b[k][j];
}
}
}
System.out.println("Resultant Matrix Is:");
for(int i=0;i<r1;i++)
{
for(int j=0;j<c1;j++)
{
System.out.print(c[i][j]);
}
System.out.println();
}
}
}
}
8|Page
Linear List:
A sequence of 0 or more homogeneous elements or a list is an ordered sequence of elements of a single type of
data. A1,A2,A3, … An where n is the length of the list. A1 is the first element and An is the last element , Ai is
the Ith element. The list may contain repeated elements more than once.
9|Page
LINKED LIST
A Linked List is a dynamic and linear data structure, which overcomes the problem raised by arrays. A
linked list is a linear data structure in which the linear ordering is maintained by links.
A linked list is a collection of nodes which maintain a linear order with links. Here, each node contains
two parts. Those are data part and reference part.
1. The data part contains the value of the data and the reference part contains link to the next node. In a
linked list, each node points to another node. So, it is enough to remember the first node in the linked
list.
2. The first node is called as “head” and the last node is called as “last”. The last node in the list contains
null as its reference field because it does not point to any other node.
3. In a linked list, each node points to another node of same type. So, the linked list, data structure is called
as self-referential structure.
4. The linked list overcomes the problems raised with arrays. An array is a static data structure and the size
of the array must be known to the compiler before the compilation.
5. An array cannot grow and shrink which means once the size is allocated for the array we can store
exactly that much of data values. We cannot store more than its size. If it stores less elements than its
size, the remaining will be wasted.
6. A linked list is dynamic data structure. We can extend the list for any number of nodes. So, the linked
list can grow and shrink.
There are several types of linked lists are available.
a. Single linked list
b. Double linked list
c. Circular linked list
d. Header linked list
Creating a Linked List: The creation of a list is the most basic operation among other operations.
Algorithm:- Creation( )
[ Initially head = null and last = null ]
Step-1: Read a value into item
Step-2: if(item = = -1) then [ end the process ]
Else
Step-2.1 : create a new node called “temp”
Step-2.2 : Insert temp.data = item , temp.link = null.
Step-2.3 : if head = = null then
head = last = temp
10 | P a g e
else
last.link = temp
last = temp
[ Repeat the process until item = = -1 ]
Step-3: Exit
Implementation:
6. item = 20
7. Since, item != -1 create a new node called temp.
10. item=30
11. Since, item != -1 create a new node called temp.
Traversing a Linked List: Visiting each and every node in the list is called traversing.
Algorithm: Traverse( )
Step-1 : set temp = head
Step-2 : while temp!=null
Step-2.1 : display temp.data
Step-2.2 : temp=temp.link
Step-3 : Exit
Implementation:
Let us consider the following linked list with four nodes.
12 | P a g e
10. Since temp=null, the process stops here.
Implementation:
Let us consider the following linked list with four nodes.
Inserting: Adding a new node to the existing list is called as inserting. We can insert a node in the following
three places.
1. Insertion at head
2. Insertion at last
13 | P a g e
3. Insertion in between any two nodes.
Insertion at head:
If the node is inserted before the head node that node becomes new head of the list.
Algorithm:- Insert-At-Head( )
Implementation:
Let us consider the following the list with four nodes.
2. Item=5, temp.data=item
temp.link=null.
3. temp.link=head
head=temp
Insertion at Last:
Algorithm: insertAtLast( )
Step-1: Create a new node called “nodex”
Step-2: Read a value into item.
Step-3: Insert nodex.data=item
nodex.link=null
Step-4: set temp=head
step-4.1: while(temp!=null)
temp1=temp
temp=temp.link
14 | P a g e
step-4.2: if(temp=null)
temp1.link=nodex
last=nodex
Step-5: Exit
Implementation:
2. item=50
3. nodex.data=item , nodex.link=null
4. temp=head
15 | P a g e
Insertion between any two nodes:
In order to insert a new node in between any two nodes we need to traverse until that node, by keeping
track of two successive nodes.
Algorithm: insertAtMiddle( )
Step-1: Create a new node called “nodex”
Step-2: Read a value into item.
Step-3: Insert nodex.data=item
nodex.link=null
Step-4: Read place to insert into place.
Step-5: set temp=head , i=1
step-5.1: while(i<place)
temp1=temp
temp=temp.link
i=i+1
step-4.2: temp1.link=nodex
nodex.link=temp.
Step-5: Exit
Implementation:
Let us consider the following the list with four nodes.
2. item=25
3. nodex.data=item and nodex.link=null
4. place=3
5. set i=1 and temp=head
16 | P a g e
7. since 2<3, temp1=temp , temp=temp.link and i=i+1
Deleting: Removing a node from the existing node is called as deleting. The deletion operation can be
performed in following three places.
1. Deleting head node
2. Deleting last node
3. Deleting a node between any two nodes.
Implementation
17 | P a g e
1. head = head.link
Algorithm: deleteLast( )
Step-1: set temp = head
Step-2: while ( temp.link != null )
temp1 = temp
temp = temp.link
Step-3: temp1.link = null
Last=temp1
Step-4: Exit
Implementation
1. temp = head
18 | P a g e
6. temp1.link = null , last = temp1
Algorithm: deleteMiddle( )
Step-1: Read place to delete into “place”
Step-2: set i=1, temp = head
Step-3: while ( i<place)
temp1 = temp
temp = temp.link
i=i+1
Step-4: temp1.link = temp.link
Step-5: Exit
Implementation
1. place = 3
2. i=1 and temp = head
19 | P a g e
Searching: The linked list is suitable only for linear search mechanism and it is not suitable for binary search
mechanism.
Algorithm: search( )
Step-1: set flag=0
Step-2: Read search value into “key”
Step-3: set temp=head
Step-4: while ( temp!=null )
if( temp.data = key )
flag=1
break the loop
temp = temp.link
Step-5: if ( flag = 1) then
Display “FOUND”
Else
Display “NOT FOUND”
Step-6: Exit
Implementation
Let us consider the following list with four nodes.
1. flag = 0
2. key = 30
3. temp = head
6. since temp != null and temp.data = 30 so flag = 1 and loop stops here.
7. Since flag = 1 we conclude that the element was found.
Creation of a node structure in Java:
We know that, a node is a self referential structure which consists of two parts.
1. Data Part 2. Reference Part
The following class is used to create a template for node structure in Java.
class Node
{
public int data;
public Node link;
20 | P a g e
Node( int x )
{
data = x;
link = null;
}
}
The individual nodes for the above template will be create as objects of the class node lile
Node temp = new Node(10);
import java.io.*;
import java.lang.*;
import java.util.*;
class Node
{
int data;
Node link;
Node(int d)
{
data=d;
link=null;
}
}
class LinkedList
{
int item;
Node first,last;
Scanner s=new Scanner(System.in);
LinkedList()
{
first=last=null;
}
void create()
{
do
{
System.out.println("Enter A Number:");
item=s.nextInt();
if(item==-1)
break;
Node temp=new Node(item);
if(first==null)
{
first=last=temp;
}
else
{
21 | P a g e
last.link=temp;
last=temp;
}
}while(item!=-1);
}
void display()
{
if(first==null)
{
System.out.println("List is empty");
return;
}
Node temp;
temp=first;
while(temp!=null)
{
System.out.println(temp.data+" -- ");
temp=temp.link;
}
}
int length()
{
int l;
Node temp=first;
for(l=1;temp!=null;l++,temp=temp.link);
return l;
}
void insert()
{
System.out.println("Enter Position:");
int pos=s.nextInt();
if(pos>0 && pos<=length())
{
System.out.println("Enter item:");
int item=s.nextInt();
Node temp=new Node(item);
if(pos==1)
{
temp.link=first;
first=temp;
}
else
{
Node prev,curr;
prev=curr=first;
int i=1;
while(i<pos)
{
prev=curr;
curr=curr.link;
22 | P a g e
i++;
}
prev.link=temp;
temp.link=curr;
}
}
else
{
System.out.println("No Such Place");
}
}
void delete()
{
if(first==null)
{
System.out.println("List is empty");
return;
}
System.out.println("Enter position:");
int pos=s.nextInt();
if(pos>0 && pos<=length())
{
if(pos==1)
{
first=first.link;
}
else
{
Node prev,curr;
prev=curr=first;
int i=1;
while(i<pos)
{
prev=curr;
curr=curr.link;
i++;
}
prev.link=curr.link;
}
}
}
void search(int key)
{
Node temp;
int flag=0;
temp=first;
while(temp!=null)
{
if(temp.data==key)
{
23 | P a g e
flag=1;
break;
}
temp=temp.link;
}
if(flag==1)
{
System.out.println("Element Found");
}
else
{
System.out.println("NOT FOUND");
}
}
}
class SLL
{
public static void main(String args[])
{
Scanner s=new Scanner(System.in);
LinkedList ll=new LinkedList();
int ch;
do
{
System.out.println("1.Creation");
System.out.println("2.Display");
System.out.println("3.Insertion");
System.out.println("4.Deletion");
System.out.println("5.Search");
System.out.println("6.Exit");
System.out.println("Enter your choice:");
ch=s.nextInt();
switch(ch)
{
case 1: ll.create();break;
case 2: ll.display();break;
case 3: ll.insert();break;
case 4: ll.delete();break;
case 5:
System.out.println("Enter Key element:");
int key=s.nextInt();
ll.search(key);
break;
case 6: System.exit(0);
default: System.out.println("Enter correct choice");
}
}while(ch<=6);
}
}
24 | P a g e
DOUBLE LINKED LIST:
In Double Linked List, each node contains two reference parts. One reference is used to remember the previous node
address and another reference is used to remember the next node address. The node in double linked list is represented as
follows.
Node
Plink Data Nlink
Plink is used to refer the previous node.
Data part contains value of the node.
Nlink is used to refer the next node.
In Double linked list, we need to remember two nodes, one is the first node called “head node”. The Plink of the head
node points to NULL. Another one is last node. The Nlink of the last node points to NULL. The following is double
linked list with four nodes.
The single linked list is used for only one way traversing whereas the double linked list is capable of traversing in both
directions, either forward or backward.
For example, if we were at node 55 in a list of 100 nodes and if we want to visit node 51. If single linked list is used we
need to start from the head node and requires 55 moves in forward direction whereas if the double linked list is used, then
we require just 4 moves backward from the node 55.
The creation of a list is the most basic operation among other operations.
Algorithm: create( )
[ initially head=NULL, last=NULL ]
Step1: Read a value into “item”
Step2: if [ item = -1 ] then
[ break the loop ]
else
Step1: Create a node called “temp”
Step2: Insert temp.data=item
temp.plink=NULL
temp.nlink=NULL
Step3: if head = = NULL, then
head = last = temp
else
last.nlink = temp
temp.plink = last
last=temp
[ Repeat the process until item = -1 ]
Step3: Exit
25 | P a g e
Implementation:
1. Initially head=NULL, last=NULL
2. Item=10
3. Since item!= -1, so
4. Create a new node called temp
7. item=20
8. since item!= -1, so
9. create a new node called temp
11. since head!= NULL ; so, last.nlink = temp ; temp.plink = last ; last = temp
12. item=30
13. since item != -1, so
14. create a new node called temp
16. since head != NULL. So, last.nlink = temp ; temp.plink = last ; temp = last
26 | P a g e
17. item = -1
18. since item = -1, so the process stops.
Traversing means visiting each and every node. A double linked list can be traversed in two ways. They are
1. Inserting at head
2. Inserting at last
3. Inserting between nodes
28 | P a g e
INSERTING AT THE HEAD:
If a node is inserted before a head node that node becomes the new head of the list.
Algorithm: insertAtHead( )
Implementation:
1. Let us consider the list with following 4 nodes.
3. Item = 5
4. temp.data= item ; temp.nlink = NULL ; temp.plink = NULL
Inserting at Last:
Algorithm: insertAtLast( )
29 | P a g e
Implementation:
1. Let us consider the list with following 4 nodes.
3. Item = 50
4. temp.data= item ; temp.nlink = NULL ; temp.plink = NULL
30 | P a g e
3. item=25
4. nodex.data = item , nodex.nlink = NULL , nodex.plink = NULL
5. place = 3
6. set i=1, temp = head
Algorithm: If a head node is deleted, then the next node becomes the new node of the list and its previous link
should points to NULL.
Algorithm: deleteHead( )
If the last node is deleted, the previous node of the last node will become the new last node of the list and the
nlink of that node should point to NULL.
Algorithm: deleteLast( )
32 | P a g e
ii. last = last.plink
In order to delete a node, we need to traverse until the node by tracking two successive nodes.
Algorithm: deleteMiddle( )
II. Place = 3
III. i = 1 , temp = head
33 | P a g e
b. since 2<=2, so, temp1 = temp , temp = temp.nlink , i=i+1
V. temp = temp.nlink
In a circular linked list, there is no beginning and there is no ending. In a circular linked list, the
reference part of the last node which means the last node points back to the first node. There is no NULL
reference in the circular linked list.
If there is a single node in the circular linked list, it points back to itself.
If it is a double linked list, the nlink of the last node refers to the head node and the plink of the head
node refers to the last node. The following is circular double linked with five nodes.
34 | P a g e
Header Linked List:
In a circular linked list, there is no beginning and there is no ending. So, while traversing a list we face a
problem because there is no NULL reference termination.
In order to solve this problem, we include the dummy reference is called “header”. The following is the
header linked list with four nodes.
Sparse Matrix:
Sparse Matrix is a matrix which contains very few non-zero elements. When the matrix size is very large
but most of the elements in it are zeros, only a small fraction of the matrix is used then that type of matrix is
called a “sparse matrix”.
0 0 0 0 9
Ex: 𝐴 = 0 8 8 0 0
4 0 0 2 0
0 0 0 0 5
For a matrix of m rows and n columns, if m=n then the matrix is called sparse square matrix.
0 0 1 0
𝐴= 2 0 5 0
0 0 0 0
0 3 4 0
Two types of n-square sparse matrices are represented as
A Matrix in which all non-zero entries occur only on or below the main diagonal is called a triangular
matrix.
35 | P a g e
10 0 0
Ex: 21 22 0 Upper triangular matrix
34 32 45
10 45 13
Ex: 0 22 55 Lower triangular matrix
0 0 45
Sparse Tridiagonal Matrix:
In this matrix, the non-zero entries can only occur on the main diagonal, the first diagonal below this and
the first diagonal above the main diagonal.
10 0 0
A= 0 22 0
0 0 45
A sparse matrix can be represented by using
1. Triplet representation
2. Linked representation
Triplet Representation:
In this representation, we consider only non-zero values along with their row and column index values.
0 0 0 0 9
𝐴= 0 8 8 0 0
4 0 0 2 0 Row(4) Column(5) Values(6)
0 0 0 0 5 0 4 9
1 1 8
1 2 8
2 0 4
2 3 2
3 4 5
In the above matrix, there are only 6 non-zero values. These values are represented by the combination of row
and column.
Linked Representation:
In linked representation, we use linked list data structure to represent a sparse matrix. In this linked list,
we use two different nodex header node and element node.
0 0 5
𝐴= 2 7 0
0 0 0
36 | P a g e
UNIT-II
STACKS:
1. A stack is a linear data structure in which the elements are processed in LIFO manner (Last In First Out)
which means the element which is inserted last will be the first one to remove.
2. The insertions and deletions in a stack can be performed at only one end. That end is called “TOP of the
stack”. The following are the list of operations that can be performed on a stack.
a. Push : The insertion operation is called as push operation.
b. Pop : The deletion operation is called as pop operation.
c. Traverse : visiting each and every data item of a stack is called traverse operation.
3. A stack is a linear list of data items which are processed as last in first out mechanism. Which means the
element which was pushed last will be the first one to pop out.
4. The following picture illustrates a stack.
OVERFLOW: Inserting an element in an already filled stack is called overflow situation. Before inserting
an element into the stack, we need to take care about the overflow situation.
UNDERFLOW: The Pop operation with an empty stack is called as underflow situation. So, before popping
an element from the stack, we need to take care about the underflow situation.
STACK USING ARRAYS: The stacks are very easily implemented with the help of arrays.
37 | P a g e
Implementation:
Push(10)
Since, 0 != 5 , so top = top + 1 and stack[top]=10
Push(20)
Since, 1 != 5 , so top = top + 1 and stack[top]=20
Push(30)
Since, 2 != 5 , so top = top + 1 and stack[top]=30
Push(40)
Since, 3 != 5 , so top = top + 1 and stack[top]=40
Push(50)
Since, 4 != 5 , so top = top + 1 and stack[top]=50
Push(60)
Since, 5 >= 5, the stack is overflow.
38 | P a g e
Implementation:
1. Pop( )
Since 4 ! = -1, so top = top – 1; display element to be out is 50. Popped
element is : 50
2. Pop( )
Since 3 ! = -1, so top = top – 1; display element to be out is 40. Popped
element is : 40
3. Pop( )
Since 2 ! = -1, so top = top – 1; display element to be out is 30. Popped
element is : 30
4. Pop( )
Since 1 ! = -1, so top = top – 1; display element to be out is 20. Popped
element is : 20
5. Pop( )
Since 0 ! = -1, so top = top – 1; display element to be out is 10. Popped
element is : 10
6. Pop( ) Since 0 > = 5, so top = top – 1 Stack is underflow.
Algorithm: Traversal
Implementation:
1. Consider the following stack. And set i=top.
39 | P a g e
3. Since i != -1display a[ i ] that is 40 and set i=i-1
import java.io.*;
import java.util.*;
class StackDemo
{
int i,top,num;
int[] a=new int[5];
Scanner s = new Scanner(System.in);
StackDemo()
{
top=-1;
}
void push()throws IOException
{
if(top==4)
{
System.out.println("Stack is overflow");
return;
}
try
{
System.out.println("Enter any number to push :");
40 | P a g e
num=s.nextInt( );
}
catch (Exception e){ }
top=top+1;
a[top]=num;
System.out.println(num + " is successfully pushed");
}
void pop()
{
if(top==-1)
{
System.out.println("Stack is underflow");
return;
}
num=a[top];
top--;
System.out.println(num + " is successfully deleted");
}
void display()
{
if(top==-1)
{
System.out.println("Stack is empty");
return;
}
for(i=top;i>=0;i--)
System.out.print("\t"+a[i]);
}
}
class StackOperations
{
public static void main(String[] args) throws Exception
{
StackDemo s=new StackDemo();
Scanner s = new Scanner(System.in);
int ch=0;
do
{
System.out.println("Stack Menu");
System.out.println("1. Push");
System.out.println("2. Pop");
System.out.println("3. Display");
System.out.println("4. Exit");
try
{
System.out.println("\tEnter your choice :\n");
ch=s.nextInt( );
}
catch (Exception e) { }
switch(ch)
41 | P a g e
{
case 1: s.push(); break;
case 2: s.pop(); break;
case 3: s.display(); break;
case 4: System.exit(0);
}
}while (ch!=4);
}
}
STACK USING LINKED LIST:
While representing stacks using linked list we have to identify only a single node that is top.
Algorithm: push( ) operation
Step-1: Read an element into item.
Create a new node temp.
Set temp.data=item , temp.link=null
Step-2: if( top = = null )
top = temp
else
temp.next=top
top=temp.
step-3: Exit
Implementation:
1. Read an element into item since top = = null
2. Item=10, create a node temp.
3. Set temp.data=item, temp.link=null
42 | P a g e
Algorithm: pop( ) operation
Implementation:
Consider the following stack as Example.
item=30
2. Since top != null , item=top.data = 20 and top=top.link
item=20
3. Since top != null , item=top.data = 10 and top = top.link.
4. Since top=null “stack is under flow”.
Algorithm: Traversal( )
Step-1: [ check for underflow ]
if ( top = = null )
display “stack is underflow”
else
temp=top
while(temp != null )
43 | P a g e
display temp.data
temp=temp.link
step-2: Exit
Implementation:
Consider the following stack with three nodes.
APPLICATIONS OF STACKS:
1. Stacks are used to evaluate arithmetic expressions. An arithmetic expression can be represented in any
one of the following three forms.
In-Fix Notation: If the operator is placed in between the operands then that is called in-fix notation.
Ex: a+b
a+b*c
Pre-Fix Notation: If the operator is preceded by the operands then it is called pre-fix notation.
Ex: +ab
44 | P a g e
*+abc
Post-Fix Notation: If the operator is followed by the operands then it is called post-fix notation.
Ex: ab+
abc*+
2. Stacks are used to convert Infix expression into postfix expression.
3. Stacks are also used in evaluate post fix expression.
4. Stacks are used in quick sort algorithm.
5. Stacks are used in recursive functions.
6. Stacks are used in solving towers of Hanoi.
7. Stacks are used to convert numbers from one number system to another number system.
8. Stacks are used to store the local variables of a block.
9. Stacks are used to store the parameters passed to a method.
10. Stacks are used to perform tree traversals.
Step-1: Start
Step-2: Push “(“ left bracket into stack and add “)” right bracket at the end of the infix string “Q”.
Step-3: Scan the expression “Q” from left to right and repeat steps 4 to 7 for each element of the “Q” till the end
of expression.
Step-4: If an operand is encountered then add it to the post fix expression “P”.
Step-5: If “(“ left bracket is encountered then push it on to the stack.
Step-6: If an operator * is is encountered
(i) Push it on to the stack
(ii) Repeatedly pop each element form stack and add it to “P” and for each operator which is having
equal precedence or higher precedence than the operator *.
Step-7: If “)” right bracket is encountered then
(i) Repeatedly pop elements form the stack till “(“ left bracket is encountered and add those to top.
(ii) Remove “(“ left bracket do not add it to top.
Step-8: Exit
Example: a*(b+c)-c/e
Q:- a*(b+c)-d/e)
SNO SYMBOL STACK EXPRESSION-P
1 A ( a
2 * (* a
3 ( (*( a
4 B (*( ab
5 + (*(+ ab
6 C (*(+ abc
7 ) (* abc+
8 - (- abc+*
9 D (- abc+*d
10 / (-/ abc+*d
11 E (-/ abc+*de
12 ) abc+*de/-
45 | P a g e
Now P: abc+*de/- is the post fix expression.
Step-1: Scan the symbol of the post fix expression P from left to right.
Step-2: Repeat the process until the stack is empty.
Step-3: If operand is encountered push it into the stack.
Step-4: If an operand is encountered pop the two elements from the stack and perform the operation and push
the result into the stack.
Step-4: Stop.
Example: 3*(12/3+2)+15/3)
SNO SYMBOL STACK EXPRESSION-P
1 3 ( 3
2 * (* 3
3 ( (*( 3
4 12 (*( 3,12
5 / (*(/ 3,12
6 3 (*(/ 3,12,3
7 + (*(+ 3,12,3,/
8 2 (*(+ 3,12,3,/,2
9 ) (* 3,12,3,/,2,+
10 + (+ 3,12,3,/,2,+,*
11 15 (+ 3,12,3,/,2,+,*,15
12 / (+/ 3,12,3,/,2,+,*,15
13 3 (+/ 3,12,3,/,2,+,*,15,3
14 ) 3,12,3,/,2,+,*,15,3/+
46 | P a g e
QUEUE
A Queue is a linear data structure which follows FIFO mechanism, which means the element which was
inserted first in to the Queue will be the first one to go out.
The insertion in Queue will be done at one end and deletion will be done at another end.
The place where insertions are made is called “rear” of the Queue.
The place where deletions are made is called “front” of the Queue.
In a Queue, the elements are inserted from rear end and deleted from front end.
The following are the list of operations that can be performed on Queue.
A Queue is a linear list of data items, which are processed as FIFO mechanism, which means the elements
ENQued will be first to be DNDued. The following picture illustrate a Queue.
OVERFLOW:
Inserting an extra element in an already filled Queue is called Overflow. Before inserting an element
into a Queue, we need to take care about the overflow.
UNDERFLOW:
The deletion operation with an empty Queue is called Underflow. So, before deleting an element from
the Queue, we need to take care about the underflow situation.
47 | P a g e
Implementation:
1. Initially front = -1 and rear = -1 and maxsize=5
2. Since (rear+1)=0>=5 is false
3. Item=10
4. Since rear = -1, so front = rear = 0
5. Q[rear]=item
48 | P a g e
Algorithm: Deletion Operation:
Implementation:
1. Let us consider the following Queue with maxzise=5.
Algorithm: Traversing:
Step-1: set i = front
Step-2: while (i<=rear)
Step-2.1: display Q[ i ]
Step-2.2: i=i+1
Step-3: Exit
Implementation:
1. Consider the following Queue with maxsize=5 and set i=front.
50 | P a g e
6. Since i<=rear is true display Q[ i ] =50 and i=i+1=5
import java.io.*;
import java.util.*;
class Queue
{
int num, front,rear,i;
int a[]=new int[5];
Scanner s = new Scanner(System.in);
Queue()
{
front=rear=-1;
}
void insert()throws IOException
{
if(rear==4)
{
System.out.println("Queue is full");
return;
}
try
{
System.out.println("Enter any number to insert :");
num=s.nextInt();
}
catch (Exception e){ }
if(front==-1)
front++;
rear++;
a[rear]=num;
System.out.println(num +" is successfully inserted...");
}
void delete()
{
if(front==-1)
{
System.out.println("Queue is empty..");
51 | P a g e
return;
}
if(front>rear)
{
System.out.println("Queue has no elements...");
front=rear=-1;
return;
}
num=a[front];
front++;
System.out.println(num +" is successfully Deleted...");
}
void display()
{
if(front==-1)
{
System.out.println("Queue is empty..");
return;
}
if(front>rear)
{
System.out.println("Queue has no elements...");
front=rear=-1;
return;
}
for(i=front;i<=rear; i++)
System.out.print("\t"+a[i]);
}
}
class QueueOperations
{
public static void main(String[] args) throws IOException
{
Queue q = new Queue();
Scanner s=new Scanner(System.in);
int ch=0;
do
{
System.out.println("Queue Menu");
System.out.println("1. Insert");
System.out.println("2. Delete");
System.out.println("3. Display");
System.out.println("4. Exit");
try
{
System.out.println("\tEnter your choice :\n");
ch=s.nextInt();
}
catch (Exception e) { }
switch(ch)
52 | P a g e
{
case 1: q.insert(); break;
case 2: q.delete(); break;
case 3: q.display(); break;
case 4: System.exit(0);
}
}while (ch!=4);
}
}
Algorithm: Deletion:
Algorithm: Traversing:
53 | P a g e
Types of Queues:
There are several types of Queues, each one is used in different type of application. The following are the
different types of Queues.
1. Circular Queues
2. Priority Queues
3. Double Ended Queues (DECueues)
CIRCULAR QUEUES:
Let us consider a situation in ordinary Queue that the max-size of the Queue is 5 and 5 insertions are
already performed and 2 deletions are performed. After performing deletions the Queue is as follows:
One more insertion operation is not permitted in the above Queue because the rear reaches the max-size of the
Queue even though there is a space left for 2 elements before front.
In order to overcome such a kind of problem, we implement Queue as a circular one. In a circular Queue
there is no beginning and there is no ending. If the rear reaches end of Queue, it move towards front and the
space utilized properly.
The circular Queues can also be implemented in two ways. 1. Using Arrays 2. Using Linked List.
1. Insertion( ) 2. Insertion( )
Item=10 Item=20
3. Insertion( ) 4. Insertion( )
Item=30 Item=40
54 | P a g e
5. Insertion( )
6. Deletion( )
Item=50
7. Deletion( ) 8. Deletion( )
Algorithm: Insertion( )
Algorithm: Deletion( )
import java.io.*;
import java.util.*;
class CQueue
{
int front, rear, count, item, i;
int a[]=new int[5];
Scanner s=new Scanner(System.in);
CQueue()
{
front=0;
rear=-1;
count=0;
}
void insert() throws IOException
{
if(count==5)
{
System.out.println("CQ is Full");
return;
}
try
{
System.out.println("Enter element to insert in CQ ");
56 | P a g e
item=s.nextInt();
}
catch (Exception e){ }
rear=(rear+1)%5;
a[rear]=item;
count++;
System.out.println(item +" is successfully inserted");
}
void delete()
{
if(count==0)
{
System.out.println("CQ is empty");
return;
}
item=a[front];
front=(front+1)%5;
count--;
System.out.println(item +" is successfully Deleted");
}
void display()
{
if(count==0)
{
System.out.println("CQ is empty");
return;
}
if(front<=rear)
{
for(i=front;i<=rear;i++)
System.out.print(a[i] +"\t");
}
if(front>rear)
{
for(i=front;i<=4;i++)
System.out.print(a[i] +"\t");
for(i=0;i<=rear;i++)
System.out.print(a[i] +"\t");
}
System.out.println("Rear="+a[rear]);
System.out.print("Front="+a[front]);
}
}
class CircularQoperations
{
public static void main(String[] args) throws IOException
{
Scanner s = new Scanner(System.in);
CQueue q=new CQueue();
57 | P a g e
int ch=0;
do
{
System.out.println("\n....Circular Queue ..\n");
System.out.println("1. Insert");
System.out.println("2. Delete");
System.out.println("3. Display");
System.out.println("4. Exit");
System.out.println("Enter your choice..");
try
{
ch=s.nextInt();
System.out.println("\n\n");
}
catch (Exception e) { }
switch(ch)
{
case 1: q.insert(); break;
case 2: q.delete(); break;
case 3: q.display(); break;
case 4: System.exit(0);
}
}while (ch!=4);
}
}
Priority Queues:
A priority queue is an abstract data type which is like regular queue data structure in which additionally
each element has a priority associated with it. In a priority queue an element with high priority is served before
an element with low priority.
Algorithm: Insertion:
Step-1: Read element and priority to item, priority
Step-2: create a new node temp and set
temp.data=item
temp.priority=priority
temp.link=null
58 | P a g e
Step-3: if ( front = = null )
front = rear = temp
else
current=previous=front
while(current!=null)
if(current.priority>temp.priority)
break
previous=current
current=current.link
if(current = = null )
rear.link=temp
rear=temp
else if( current = = front )
temp.next=front
front=temp
else
previous.next=temp
temp.next=current
Algorithm: Deletion:
Step-1: if(front = = null)
display “Underflow”
else
display front.data
front=front.link
Algorithm: Display:
Step-1: [ check for underflow ]
if(front = = null)
display “underflow”
Step-2: set temp=front
while(temp!=null)
display temp.data
display temp.priority
temp=temp.link
Applications of Queues:
1. Queues are used in CPU scheduling.
2. Queues are used in Disk scheduling.
3. Queues are used in IO Buffers to transfer data.
4. Queues are also used in pipes to transfer data.
5. Queues are used in file IOs.
59 | P a g e
UNIT-III
TREES
Definition: A tree is a non-linear data structure used to represent one to many relationships with data items. A
tree is used to represent hierarchical relationships.
Terminology:
Sub Tree A tree which is formed by excluding its roots and contains all other nodes and edges is
called sub tree.
Height of the Tree The total no.of edges involved from the root to its last leaf node is called
“height”.
60 | P a g e
SOME VARIANTS OF TREES:
1 Binary Tree:
A tree T is said to be binary tree if there exists exactly 0,1,2 children nodes for each node of the tree i.e.,
the number of children of a node is at most 2.
2 2-Tree:
A binary tree is said to be an 2-tree if and only if there exists exactly 0,2 children for every node.
The number of children of A,B,C is 2 and the number of children of D,E,F,G are 0.
A binary tree is said to be balanced tree if the height of the left sub-tree differs one with the height of
right sub-tree.
61 | P a g e
BINARY TREE TRAVERSALS:
There are three different types of traversing techniques to traverse a binary tree. Traversing means
visiting each and every node of a tree. The following are the different traversing techniques.
1. In-order traversal
2. Pre-order traversal
3. Post-order traversal
In-Order Traversal:
In this traversing technique the left sub-tree visited first followed by its root and then the right sub-tree is
visited. The following is the sequence of visiting order for an in-order traversal.
Left Right
Root
sub-tree sub-tree
Recursive Algorithm for In-Order Traversal:
Step-1: visit left sub-tree (root.lchild)
Step-2: visit root (root.data)
Step-3: visit right sub-tree (root.rchild)
Step-4: exit
Implementation:
HCBDAFEGIJ
Pre-Order Traversal:
In this traversing technique, the root of the tree is visited first and followed by left sub-tree and then
right sub-tree is visited. The following is the sequence of visiting order of pre-order traversal.
Left Right
Root
sub-tree sub-tree
62 | P a g e
Implementation:
ABCHDEFGIJ
Post-Order Traversal:
In this traversing technique, the left sub-tree is visited first and then right sub-tree is visited and then
root is visited. The following is the sequence of visiting order of post order.
Left Right
Root
sub-tree sub-tree
Implementation:
HCDBFJIGEA
Binary-Tree Representation:
A binary tree data structure is represented in two ways.
a. Array representation
b. Linked list representation
63 | P a g e
Array Representation:
In array representation of binary tree, we use one-dimensional array. Let‟s consider the following tree.
1. Store the left child at 2*i+1 position, if its parent node is at ith position.
2. Store the right child at 2*i+2 position, if its parent node is at ith position.
3. We need one-dimensional array with a maximum size of 2n+1-1, to represent a binary tree of depth „n‟.
4. The above example is represented as follows.
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
A B C D E F G H I - - - J - - -
Linked Representation:
We use double linked list to represent binary tree. In a double linked list, every node consists of three
fields. First field is used to store the left child address, second field is used to store data, third field is used to
store right child address.
64 | P a g e
The binary search tree of above data is as follows:
Tree Traversal:
There are three different kinds of traversing techniques to traverse a tree. Traversing means visiting each
and every node.
In-Order Traversal:
In this traversal, the left sub-tree us visited first followed by its root and then the right sub-tree is visited.
1. Visit the left sub-tree
2. Visit root node
3. Visit the right sub-tree
Left Right
Root
sub-tree sub-tree
Recursive algorithm for In-order traversal:
Step-1: visit left sub-tree inorder(root.lchild)
Step-2: visit root node ( display root.data)
Step-3: visit right sub-tree inorder(root.rchild)
In-Order : 10 14 25 35 40 45 50 65
Pre-Order Traversal:
In this traversal, the root node of the tree is visited first followed by left sub-tree and then right sub-tree.
1. Visit root node
2. Visit left sub-tree
3. Visit right sub-tree
Left Right
Root
sub-tree sub-tree
65 | P a g e
Recursive algorithm for Pre-Order traversal:
Step-1: visit root node (display root.data)
Step-2: visit left sub-tree preorder(root.lchild)
Step-3: visit right sub-tree preorder(root.rchild)
Pre-Order : 35 14 10 25 40 50 45 65
Post-Order:
In this traversal, left sub-tree is visited first and then the right sub-tree then the root node is visited.
1. Visit left sub-tree
2. Visit right sub-tree
3. Visit root node
Left Right
Root
sub-tree sub-tree
Recursive algorithm for Post-Order traversal:
Step-1: visit left sub-tree postorder(root.lchild)
Step-2: visit right sub-tree postorder(root.rchild)
Step-3: visit root node (display root.data)
Post-Order : 10 25 14 45 65 50 40 35
66 | P a g e
c. Deleting a node with two Childs
4. Traversing a BST.
a. In-Order
b. Pre-Order
c. Post-Order
5. Minimum element in BST
6. Maximum element in BST
Implementation:
1. Initially root=null, item=47
2. Create a new node called nodex
5. Read item=39
6. Create a new node called nodex
68 | P a g e
18. since root != null set temp = root
19. since nodex.data < temp.data and temp.lchild!=null set temp=temp.lchild.
26. Since nodex.data < temp.data and temp.lchild = null set temp.lchild=nodex.
69 | P a g e
import java.lang.*;
import java.io.*;
import java.util.*;
class Node
{
int data;
Node rchild,lchild;
Node(int d)
{
data=d;
rchild=null;
lchild=null;
}
}
class BinarySearchTree
{
Node root;
Scanner s=new Scanner(System.in);
BinarySearchTree()
{
root=null;
}
void insert()
{
System.out.print("Enter item:");
int item=s.nextInt();
Node nodex=new Node(item);
if(root==null)
{
root=nodex;
}
else
{
Node temp=root;
while(true)
{
if(nodex.data<temp.data)
{
if(temp.lchild==null)
70 | P a g e
{
temp.lchild=nodex;
break;
}
else
{
temp=temp.lchild;
}
}
else
{
if(temp.rchild==null)
{
temp.rchild=nodex;
break;
}
else
{
temp=temp.rchild;
}
}
}
}
System.out.println("Element Inserted Succuessfully");
}
void inorder(Node temp)
{
if(temp!=null)
{
inorder(temp.lchild);
System.out.print(temp.data+" ");
inorder(temp.rchild);
}
}
void preorder(Node temp)
{
if(temp!=null)
{
System.out.print(temp.data+" ");
preorder(temp.lchild);
preorder(temp.rchild);
}
}
void postorder(Node temp)
{
if(temp!=null)
{
postorder(temp.lchild);
postorder(temp.rchild);
System.out.print(temp.data+" ");
71 | P a g e
}
}
}
class BST
{
public static void main(String args[])
{
BinarySearchTree bst=new BinarySearchTree();
Scanner s=new Scanner(System.in);
int ch;
do
{
System.out.println("1.Insert");
System.out.println("2.Inorder");
System.out.println("3.PreOrder");
System.out.println("4.PostOrder");
System.out.println("5.Exit");
System.out.println("Enter your choice:");
ch=s.nextInt();
switch(ch)
{
case 1: bst.insert();break;
case 2: bst.inorder(bst.root);break;
case 3: bst.preorder(bst.root);break;
case 4: bst.postorder(bst.root);break;
case 5: System.exit(0);
default: System.out.println("Invalid choice");
}
}while(ch<=5);
}
}
72 | P a g e
To delete a node temp1 which is left-child to temp, we need to set temp.lchild=null.
To delete a node temp which is having one child, we need to set temp1.rchild=temp.rchild, then
In the above example if you want to delete node 12, then the minimum element in the right sub tree is 19.
Replace 12 with 19. Here only values are replaced. Now the tree becomes
73 | P a g e
Remove the 19 from the right sub-tree.
74 | P a g e
Consider the above binary tree. We need to keep null values in left-child reference of left most node and right-
child reference of right most node.
The problem with above representation is that we can‟t find the direct child and parent node references. In-order
to achieve this we need to rearrange the node structure as follows:
75 | P a g e
Heap Tree:
Heap data structure is a specialized binary tree based data structure. Hence it is a binary tree with special
characteristics. In a heap data structure, nodes are arranged based on their values.
A heap data structure, sometimes called as binary heap. There are two types of heap data structure, they
are
1. Max Heap
2. Min Heap
Every Heap data structure has the following properties.
Property-1:- ORDERING: Nodes must be arranged in a order according to values based on max heap or min
heap.
Property-2:- STRUCTURAL: All levels in a heap must be full, except last level and nodes must be filled from
left to right strictly.
MAX-HEAP:
Max-Heap is a specialized full binary tree in which every parent node contains greater value or equal
value than its child nodes. In Max heap, the value of the root node is greater than or equal to either of its
children.
Above tree is satisfying both ordering property and structural property according to the Max-Heap data
structure.
The following operations are performed in Max-Heap data structure:
1. Finding maximum
2. Insertion
3. Deletion
Insertion operation in Max-Heap:
Step-1: Insert the new node as last leaf from left to right
Step-2: Compare new node with its parent node.
Step-3: If new node value is greater than its parent node value then swap both values.
Step-4: repeat step-2 and step-3 until new node value is less than its parent node or new node reached root.
MIN-HEAP:
Min-Heap tree is a specialized full binary tree in which every parent node contains less value or equal
value than its child nodes. In Min-Heap tree, value of the root node is less than or equal to either of its children.
76 | P a g e
The following operations are performed on Min-Heap data structure.
1. Finding the minimum
2. Insertion
3. Deletion
Insertion operation in Min-Heap:
Step-1: Insert the new node as last leaf from left to right
Step-2: Compare new node with its parent node.
Step-3: If new node value is less than its parent node value then swap both values.
Step-4: repeat step-2 and step-3 until new node value is greater than its parent node or new node reached root.
77 | P a g e
UNIT-IV
GRAPHS
A graph is a non-linear data structure and is represented as G(V,E) where V is the set of vertices and E is
the set of edges. Graph data structure is used to represent many to many relationships with the data items. A
vertex is nothing but data element and edge is nothing but a connection between every verex.
Every tree forms a graph but every graph need not be a tree. A tree with atleast one cycle forms a graph.
V= {A,B,C,D,E}
E= {AB,BC,CD,DE,AE,BD}
Terminology:
1. Path:
The edges involved in connection between any pair of vertices is called path. In the above
example the edges AB,BD forms a path between the vertices A and D.
2. Isolated Vertex:
A vertex which does not have any edges connect to it os called isolated vertex. In the below
example D is called isolated vertex.
3. Undirected Graph:
A graph G(V,E) is called an undirected graph, if there is no specified direction for the edges.
78 | P a g e
5. In-degree of a graph:
For a directed graph, the number of edges incident with vertex is called its in-degree. The in-
degrees of vertices of the above graph is shown below.
In-Degree of A is 0
B is 2
C is 1
D is 2
E is 2
6. Out-degree of a graph:
For a directed graph, the number of edges eliminating from a vertex is called out-degree. The
out-degree of vertices of the above graph is shown below.
Out-Degree of A is 2
B is 2
C is 1
D is 1
E is 1
7. Loop (or) Cycle:
A path which starts from a vertex and ends with the same vertex forms a cycle.
8. Self-Loop:
A vertex which has an edge with itself is called as self loop.
9. Weighted Graph:
A graph G(V,E) is called a weighted graph, if there is a positive integer assigned to each and
every edges of a graph.
Adjacency Matrix:
In this representation, a graph is represented as a 2-dimensional array of size n x n, where n is the
number of vertices in the graph. The element value is represented as 1 if there is an edge between the two
vertices otherwise 0.
Consider the following digraph and its equivalent adjacency matrix.
79 | P a g e
If the graph is an undirected graph, we obtain a matrix such as Aij = Aji for all i,j such a matrix is called
symmetric matrix.
For a weighted graph instead of representing one value we place its weight in the matrix.
Adjacent List:
The adjacency matrix representation contains more number of zero entries. A matrix with more number
of zero elements is called sparse matrix.
So there is a lot of waste storage space. To overcome this problem, a graph is represented with the help
of linked list.
80 | P a g e
Depth First Search (DFS):
In this traversing technique, we start at a vertex and a neighbor vertex is visited in an order. The DFS
algorithm uses STACK data structure to process the vertices. In this mechanism each vertex maintains three
status values.
status = 0 ( unvisited vertex )
status = 1 ( currently visited vertex )
status = 2 ( already visited vertex )
Algorithm:
Step-1: Initialize the status set „S‟ with zero for all vertices. Since all vertices are in unvisited state.
Step-2: Choose any vertex and push into the stack and update its status to one in the status set „S‟.
Step-3: pop the top most element from the stack and push all of its neighbors into the stack and update the status
of popped element to 2 and update status of pushed elements to 1 in the status set „S‟.
Step-4: Display the popped element.
Step-5: Repeat step-3 and step-4 until either stack is empty or status of all elements become 2.
Implementation:
1. Let us consider the following digraph with 7 vertices.
81 | P a g e
Pop the top element from the stack while
pushing all of its neighbors into stack and
update the status of popped element to 2 and Status set S = { 2, 1, 2, 1, 2, 1, 2 }
pushed elements to 1. So E is visited.
AGCEDFB
Breadth First Search (BFS):
In this traversing technique, we start at a vertex and a neighbor vertex is visited in an order. The DFS
algorithm uses QUEUE data structure to process the vertices. In this mechanism each vertex maintains three
status values.
status = 0 ( unvisited vertex )
status = 1 ( currently visited vertex )
status = 2 ( already visited vertex )
Algorithm:
Step-1: Initialize the status set „S‟ with zeros which indicates all the vertices are in unvisited state.
Step-2: Choose any vertex and insert into the Queue and update its status to one in the set „S‟.
Step-3: Delete the front element from the Queue while inserting all of its neighbors whose status is at zero into
the Queue at rear and update the status of deleted element to 2 and update the status of inserted elements
to 1 in set „S‟.
Step-4: Display the deleted element.
Step-5: Repeat steps 3 and 4 until the queue is empty or the status of all elements becomes 2.
Implementation:
1. Let us consider the following digraph with seven vertices.
The vertex set V = { A, B, C, D, E, F, G }
Status set S={0,0,0,0,0,0,0}
and Queue is empty.
82 | P a g e
Let the chosen vertex be „A‟
Status set S = { 1, 0, 0, 0, 0, 0, 0 }
83 | P a g e
Since the Queue is empty and status set contains all twos so the process stops here. The BFS traversal results
the following sequence of vertices.
AGCEDFB
Spanning Trees:
A tree which is formed by all the vertices and only with (n-1) edges, if there are n vertices in the graph
𝑛 (𝑛−1)
is called spanning tree. For a connected graph with n vertices there are 2 spanning trees.
84 | P a g e
Implementation:
Let us consider the following weighted graph with 6 vertices.
85 | P a g e
Edge Weight Status
BE 1 1(select)
AB 2 1(select)
DF 3 0
AE 3 0
AF 4 0
CF 4 0
BD 5 0
CD 6 0
ED 6 0
BC 7 0
86 | P a g e
Edge Weight Status
BE 1 1(select)
AB 2 1(select)
DF 3 1(select)
AE 3 0(reject)
AF 4 1(select)
CF 4 1(select)
BD 5 0
CD 6 0
ED 6 0
BC 7 0
8. The one more edge inclusion forms a cycle. So the process is stopped here.
Therefore the total cost of minimum spanning tree is 1+2+3+4+4=14. The Kruskal‟s algorithm does not
guarantee tree to be a connected one.
PRIM‟S ALGORITHM:
This algorithm was introduced by V.I.Primi.
Algorithm:
Step-1: Initialize all the vertices with no edges.
Step-2: Take a set S which is to contain the nodes of a tree initially it is empty.
Step-3: Choose the least cost edge which starts from the element of the set S which are not in the set S.
Step-4: Add the vertex to the tree, if it does not form a cycle and also add it to the set S.
Step-5: Repeat the steps 4 and 5 until (n-1) edges are selected.
Implementation:
Let us consider the following graph with 6 vertices.
87 | P a g e
1. Initialize all the vertices with no edges.
88 | P a g e
7. The least among BD,BC,ED,FC,FD is FD. So set S={A,B,E,F,D}
Now, set contains all the vertices of the graph. So the process will stopped here. Therefore the total cost of
minimum spanning tree is 2+1+4+4+3=14.
89 | P a g e
UNIT-V
SEARCHING & SORTING
SEARCHING:
It is the most important operation in the field of computer science. Searching means finding the required
element from a group of elements. The searching element is called as key element.
There are two types of searching mechanisms. Those are
1. Linear Search
2. Binary Search
LINEAR SEARCH:
As the name implies, the linear search works in a sequential order from the first element to the required
element or till to the end of the group. The linear search compares the key element with the group elements one
by one until either a match has been found or the list becomes end.
Let us consider the following example.
key=29.
1. The search process starts at a[0], which is compared with key. Since a[0] ≠ key we move to the next
element.
2. Now a[1] is compared with key element. Since a[1] ≠ key we move on to the next element.
3. Now a[2] is compared with key element. Since a[2] = key we stop the search process.
Algorithm:
Step-1: Read list of element into array a with size n.
Step-2: set i = 0 , flag = 0
Step-3: Repeat while(i<n)
if(a[i] = key) then
set flag=1 and break the loop.
Set i=i+1
Step-4: if flag= = 1 then
Display “element found”
else
display “element not found”
step-5: Exit.
Time Complexity:
Time complexity determines the amount of time required for the algorithm to execute. It can be measured in
three cases.
1. Best Case: Least possible amount of time. In linear search this case occurs, if the key element was
founded at the first location. So, the time complexity is O(1).
2. Worst Case: Highest possible amount of time. In linear search, this case occurs, if the key element is the
last element or not there in the list. So the time complexity is O(n).
3. Average Case: Average possible amount of time. In linear search, this case occurs if the key element
was found in between first and last element. So, the time complexity is O(n/2).
90 | P a g e
import java.lang.*;
import java.io.*;
import java.util.*;
class LinearSearch
{
public static void main(String args[])
{
Scanner s=new Scanner(System.in);
System.out.print("Enter array size:");
int n=s.nextInt();
int a[]=new int[n];
System.out.println("Enter array elements:");
for(int i=0;i<n;i++)
a[i]=s.nextInt();
System.out.print("Enter element to search:");
int key=s.nextInt();
int flag=0;
for(int i=0;i<n;i++)
{
if(a[i]==key)
{
flag=1;
break;
}
}
if(flag==1)
System.out.println("Element Found");
else
System.out.println("Element not Found");
}
}
Binary Search:
It is a divide and conquer technique. In binary search, the search process always focused on middle
element of the list. In-order to perform binary search, the elements of the list should be arranged in a sorted
order.
In binary search, first we calculate the location of the middle element. Then that element is compared
with key element. Then any one of the following three cases may occur.
1. If the key element is equal to the middle element, then we conclude that the element was found and will
stop the searching process.
2. If the key element is less than middle element then we divide the array from the first element to middle
element and repeat the same process by calculating middle element.
3. If the key element is greater than middle element, then we divide the array from middle element to last
element and repeat the same process by calculating middle element.
Algorithm:
Step-1: Read list of elements into array a with size n in sorted order.
Step-2: set start=0 and end=n-1 flag=0
Step-3: Repeat until (start<=end)
Calculate mid=(start+end)/2
91 | P a g e
If(a[mid]>key) then end=mid-1
If(a[mid]<key) then start mid+1
If(a[mid])==key then set flag=1 and break the loop
Step-4: if(flag==1) then
Display” element found”
Else
Display “Element not found”
Step-5: Exit
Time Complexity:
1. Best Case: O(1)
2. Worst Case: O(log n +1)
3. Average Case: O(logn)
import java.lang.*;
import java.io.*;
import java.util.*;
class BinarySearch
{
public static void main(String args[])
{
Scanner s=new Scanner(System.in);
System.out.print("Enter array size:");
int n=s.nextInt();
int a[]=new int[n];
System.out.println("Enter array elements:");
for(int i=0;i<n;i++)
a[i]=s.nextInt();
System.out.print("Enter element to search:");
int key=s.nextInt();
int start=0,end=n-1,mid;
int flag=0;
while(start<=end)
{
mid=(start+end)/2;
if(a[mid]==key)
{
flag=1;
break;
}
else if(a[mid]<key)
start=mid+1;
else
end=mid-1;
}
if(flag==1)
System.out.println("Element Found");
else
System.out.println("Element not Found");
}
}
92 | P a g e
SORTING
Sorting refers to arrangement of data items either in ascending order or in descending order. Sorting is
the most primitive operation in data organization.
For example inorder to perform binary search among n elements we need to arrange those elements in
an order. There are several kinds of sorting algorithms.
1. Bubble Sort
2. Selection Sort
3. Insertion Sort
4. Quick Sort
5. Merge Sort
6. Heap Sort
BUBBLE SORT:
It is the most easiest sorting algorithms used with small number of elements. In bubble sort technique,
each time the consecutive elements are compared and swapping takes place if necessary i.e., a[0] is compared
with a[1], a[1] is compared with a[2] and so on.
At the end of pass-1(iteration) the highest element of the list will be in its proper position i.e., a[n-1] is filled
with highest element, again we have to repeat the same procedure for remaining n-1 elements. At the end of
each iteration we found that the consecutive highest element will get their proper place.
Let us consider the following example to implement bubble sort with an array a of 5 elements.
PASS-1:
In this pass a[0] is compared with a[1], a[1] is compared with a[2], a[2] is compared with a[3], a[3] is
compared with a[4]. Whenever greater than condition is true then swapping of those two elements will
be performed.
PASS-2:
In this pass a[0] is compared with a[1], a[1] is compared with a[2], a[2] is compared with a[3].
Whenever greater than condition is true then swapping of those two elements will be performed.
93 | P a g e
PASS-3:
In this pass a[0] is compared with a[1], a[1] is compared with a[2]. Whenever greater than condition is
true then swapping of those two elements will be performed.
PASS-4:
In this pass a[0] is compared with a[1]. Whenever greater than condition is true then swapping of
those two elements will be performed.
As the end of pass-4 the 4th highest element is in a[1] position. The number of comparisons in pass-4 is 1. The
total number of passes is 4 and total number of comparisons in all the passes is 10.
If there are n elements in the array then the total number of comparisons required for bubble sort is n(n-1)/2.
Time Complexity:
Base Case: O(n)
Worst Case: O(n2)
Average Case: O(n2)
Algorithm:
Step-1: Read list of elements into an array of size n.
Step-2: loop for i=0 to n-1 each time increase i by 1
Step-3: loop for j=0 to n-1-I each time increase j by 1
Step-4: if a[j]>a[j+1] then
temp=a[j]
a[j]=a[j+1]
a[j+1]=temp
step-5: exit
94 | P a g e
import java.lang.*;
import java.io.*;
import java.util.*;
class BubbleSort
{
public static void main(String args[])
{
Scanner s=new Scanner(System.in);
System.out.println("Enter array size:");
int n=s.nextInt();
int a[]=new int[n];
System.out.println("Enter array elements:");
for(int i=0;i<n;i++)
a[i]=s.nextInt();
for(int i=0;i<n-1;i++)
{
for(int j=0;j<n-i-1;j++)
{
if(a[j]>a[j+1])
{
int temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
System.out.print("Elements in Sorted Order are:");
for(int i=0;i<n;i++)
System.out.print(a[i]+" ");
}
}
SELECTION SORT:
It is the most easiest sorting algorithm used with small number of elements. In selection sort techniques, each
time one element is compared with all the remaining elements and swapping takes place if necessary i.e., a[0] is
compared with a[1],a[2],..a[n-1] and a[1] is compared with a[2],a[3]… and a[n-1]. At the end of pass-1, the
lowest element of the list will be in its proper position i.e., a[0].
Again we have to repeat the same process with a[1] for remaining elements. At the end of each iteration we find
that the consecutive lowest element will be placed in their proper places.
Let us consider the following example to implement selection sort with an array of 5 elements.
95 | P a g e
PASS-1:
In this pass a[0] is compared with a[1],a[2],a[3] and a[4]. If a[0] greater than any of the element then
swapping will be takes place.
PASS-2:
In this pass a[1] is compared with a[2],a[3] and a[4]. If a[1] greater than any of the element then
swapping will be takes place.
PASS-3:
In this pass a[2] is compared with a[3] and a[4]. If a[2] is greater than any of the element then
swapping will be takes place.
96 | P a g e
PASS-4:
In this pass a[3] is compared with a[4]. If a[3] is greater than a[4] then swapping will be done.
Time Complexity:
Best Case : O(n)
Worst Case : O(n2)
Average Casse : O(n2)
Algorithm:
Step-1: Read a list of elements into an array of size n.
Step-2: loop i=0 to n-1 each time increment i by 1
Step-3: loop j=i+1 to n-1 each time increment j by 1
Step-4: if a[i] > a[j] then
temp=a[i]
a[i]=a[j]
a[j]=temp
Step-5: Exit
import java.lang.*;
import java.io.*;
import java.util.*;
class SelectionSort
{
public static void main(String args[])
{
Scanner s=new Scanner(System.in);
System.out.println("Enter array size:");
int n=s.nextInt();
int a[]=new int[n];
System.out.println("Enter array elements:");
for(int i=0;i<n;i++)
a[i]=s.nextInt();
for(int i=0;i<n-1;i++)
{
for(int j=i+1;j<n;j++)
{
if(a[i]>a[j])
{
int temp=a[i];
a[i]=a[j];
97 | P a g e
a[j]=temp;
}
}
}
System.out.print("Elements in Sorted Order are:");
for(int i=0;i<n;i++)
System.out.print(a[i]+" ");
}
}
INSERTION SORT:
It is another kind of most efficient sorting algorithm. This algorithm begins with taking first element of the list
as in its proper place i., in sorted list and the remaining all elements will be considered as unsorted list.
Then first element of the unsorted list will be compared with sorted list and if it is less than the value in sorted
list then swapping will be performed. This process will be continued until unsorted list will become empty.
Let us consider the following list in to an array of size 5.
PASS-1: In this pass a[1] will be a[0]. Since a[0] < a[1] then a[1] will be taken into sorted list without
swapping.
PASS-2: In this pass a[2] is compared with a[1]. Since a[1] > a[2] then swapping will be performed.
After swapping a[1] and a[0] are compared. Since a[0] > a[1] then again swapping will be performed.
98 | P a g e
PASS-3: In this pass a[3] is compared with a[2]. Since a[2] > a[3] then swapping will be performed.
After swapping a[2] is compared with a[1]. Since a[1] < a[2] then this will be completed.
PASS-4: In this pass a[4] is compared with a[3]. Since a[3] > a[4] swapping will be performed.
After swapping a[3] is compared with a[2]. Since a[2] >a[3] again these two elements will be swapped.
After swapping a[2] is compared with a[1]. Since a[1] >a[2] again these two elements will be swapped.
After swapping a[1] is compared with a[0]. Since a[0] >a[1] again these two elements will be swapped.
Algorithm:
Step-1: Read a list values into an array of size n.
Step-2: loop for i=1 to n-1 each time increment i by 1.
Step-3: set value=a[i] and place =i
Step-4: Repeat step-5 until place > 0 and a[place-1] > value
Step-5: a[place]=a[place-1]
Place=place-1
Step-6: a[place]=value
Step-7: Exit
import java.lang.*;
import java.io.*;
import java.util.*;
class InsertionSort
{
public static void main(String args[])
99 | P a g e
{
Scanner s=new Scanner(System.in);
System.out.println("Enter array size:");
int n=s.nextInt();
int a[]=new int[n];
System.out.println("Enter array elements:");
for(int i=0;i<n;i++)
a[i]=s.nextInt();
int place,value;
for(int i=1;i<n;i++)
{
place=i;
value=a[i];
while(place>0 && a[place-1]>value)
{
a[place]=a[place-1];
place=place-1;
}
a[place]=value;
}
System.out.print("Elements in Sorted Order are:");
for(int i=0;i<n;i++)
System.out.print(a[i]+" ");
}
}
QUICK SORT:
This is the most efficient and fastest sorting procedure when compared to all other sorting algorithms.
This sorting algorithm uses divide and conquer approach of the elements of the array to arrange them either in
ascending order or in descending order.
In this algorithm the array will be portioned into two parts based on pivot element.
On each step the pivot element will be placed in correct location and hence the array will be divided into
two parts. Those are before pivot element and after the pivot element.
The same process is repeated for both parts and therefore again these two parts will be divided and same
process is repeated for these subparts until the size of the sub part become 1.
It is very clear that the algorithm is completely based on portioning approach for the pivot element.
Algorithm:
Step-1: Read a list of values into an array of size n.
Step-2: set i=low and j=high+1
Step-3: if low < high
Set pivot=a[low]
Step-3.1: Repeat while a[i] < pivot and i < hight, i++
Step-3.2: Repeat while a[j]>pivot and j>=high, j - -
Step-3.3: if(i<j) then
Temp=a[i]
a[i]=a[j]
a[j]=Temp
Repeat until 3.1, 3.2, 3.3 otherwise stop the loop.
100 | P a g e
Step-3.4: swap pivot and a[j]
Quick(a,low,j-1)
Quick(a,j+1,high)
Step-4: Exit
import java.io.*;
import java.lang.*;
import java.util.*;
class QuickSort
{
private static void qsort(int[] arr,int left,int right)
{
int index=partion(arr,left,right);
if(left<index-1) qsort(arr,left,index-1);
if(index<right) qsort(arr,index,right);
}
private static int partion(int[] arr,int left,int right)
{
int pivot=arr[(left+right)/2];
while(left<=right)
{
while(arr[left]<pivot) left++;
while(arr[right]>pivot) right--;
if(left<=right)
{
int temp=arr[left];
arr[left]=arr[right];
arr[right]=temp;
left++;
right--;
}
}
return left;
}
public static void main(String[] args)
{
Scanner s=new Scanner(System.in);
System.out.println("Enter array size:");
int n=s.nextInt();
int a[]=new int[n];
System.out.println("Enter array elements:");
for(int i=0;i<n;i++)
a[i]=s.nextInt();
qsort(a,0,n-1);
System.out.print("Sorted List:");
for(int i=0;i<n;i++)
System.out.print(a[i]+" ");
}
}
101 | P a g e
MERGE SORT:
Merge sort technique sort technique can be implemented in two ways.
1. We can take two sorted lists and then form a new sorted list by arranging the two sorted lists into one
list.
2. We will divide the list into two parts until the sub-list contains single values and then merging them in a
sorted order. While merging place lower values in left hand side and larger values in right hand side.
44 29 25 35 56 77 42 39
44 29 25 35 56 77 42 39
44 29 25 35 56 77 42 39
44 29 25 35 56 77 42 39
29 44 25 35 56 77 39 42
25 29 35 44 39 42 56 77
25 29 35 39 42 44 56 77
Algorithm:
102 | P a g e
import java.lang.*;
import java.util.*;
import java.lang.*;
class MergeSort
{
int[] array;
int[] temp;
int length;
public void sort(int[] arr)
{
this.array=arr;
this.length=arr.length;
this.temp=new int[length];
merge_sort(0,length-1);
}
public void merge_sort(int low,int high)
{
if(low<high)
{
int mid=(low+high)/2;
merge_sort(low,mid);
merge_sort(mid+1,high);
merge(low,mid,high);
}
}
public void merge(int low,int mid,int high)
{
for(int i=low;i<=high;i++)
temp[i]=array[i];
int i=low;
int j=mid+1;
int k=low;
while(i<=mid && j<=high)
{
if(temp[i]<=temp[j])
{
array[k]=temp[i];
i++;
}
else
{
array[k]=temp[j];
j++;
}
k++;
}
while(i<=mid)
{
array[k]=temp[i];
i++;
103 | P a g e
k++;
}
}
public static void main(String args[])
{
Scanner s=new Scanner(System.in);
MergeSort ms=new MergeSort();
System.out.println("Enter array size:");
int n=s.nextInt();
int a[]=new int[n];
System.out.println("Enter elements:");
for(int i=0;i<n;i++)
a[i]=s.nextInt();
ms.sort(a);
System.out.print("Elements in Sorted Order:");
for(int i=0;i<n;i++)
System.out.print(a[i]+" ");
}
}
Applications of Trees:
1. Trees are used to manipulate hierarchical data.
2. Tree traversing techniques makes it easy to search information.
3. Trees are used to manipulate sorted lists of data.
4. Trees are used to represent phrase structure of sentences, which is crucial to language processing
programs.
5. An operating system maintains disk‟s file system as a tree, where file folders act as tree nodes. The tree
structure is useful because it easily accommodates the creation and deletion of folders and files.
Applications of Graphs:
Applications of graphs include computer networks, electrical circuits, transport networks, molecular
structures and Data bases.
1. Graphs are good in modeling real world problems like representing cities which are connected by roads
and finding the paths between cities, modeling air traffic controller system, railway lines etc
2. In computer Networks Work stations and Servers can be viewed as Vertices.
3. Graph theory may be used to configure for optimum performance.(Shortest path First)
4. Graphs are often useful to represent Entity Relationship Diagram (ERD) used in design of Database.
5. Electrical circuits, molecular structures are also applications of Graphs.
104 | P a g e