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

Ds Study Material (Java)

The document discusses different abstract data types and data structures. It defines abstract data types and describes linear and non-linear data structures. It also provides details about arrays, linked lists, stacks, queues, trees and graphs.

Uploaded by

rojamani ganta
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views

Ds Study Material (Java)

The document discusses different abstract data types and data structures. It defines abstract data types and describes linear and non-linear data structures. It also provides details about arrays, linked lists, stacks, queues, trees and graphs.

Uploaded by

rojamani ganta
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 104

UNIT I

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.

STRUCTURED DATA TYPES:


Structure data types can hold a collection of data values. This collection will generally consist of the
primitive data types.
Arrays, structures, classes and Files are referred as structure data types.
Structure data types are created by programmers and are referred as the building blocks of data
structures.

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

Linear Data Structures:


The Data structures where the data elements are organized in some sequence is called linear data
structures. Here, the various operations on data structure are possible only in a sequence.
1. Examples of linear data structures are arrays, stacks, queues and linked lists.
2. They can be implemented in memory in two ways.
3. The first method is by having a linear relationship between elements by means of sequential memory
locations.
4. The second method is by having a linear relationship by using links.

Non-Linear Data Structures:


3|Page
The Data structure where data elements are organized in some arbitrary functions without any sequence,
such data structures are called non-linear data structures.
1. Examples of such types are Graphs and Trees
2. The relationship adjacency is not maintained between elements of a 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

i. One data item acts as root for others.


4|Page
ii. There should exist one path between any pairs of nodes. (It doesn‟t form any cycle).

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

The following figure will illustrate the concept of an array.

One Dimensional Array


Creation of an array involves three steps.
1. Declaration of array
2. Creation of memory locations to the array
3. Initialization of array elements

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.

Creation of Memory Location:


After declaring the array, we need to create memory locations to the declared array. Java allows to create
memory locations with the help of „new‟ keyword.

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.

data-type array-name [ ] = new data-type [ size ];

int a[ ] = new int [10];

Initialization of Array elements:


After creating memory locations we need to assign values to array elements. This process is called Initialization.
We can assign values to individual elements with the help of its subscript as follows.

a[0] = 10
a[1] = 20
a[2] = 30

Like other variables an array can also be initialized on declaration as follows.


Syntax:
data-type array-name [ ] = { list of values };
Examples:
int a [ 5 ] = {1,2,3,4,5};
In the above example, the array has been given values which will be stored from a[0] to a[4].
length is a variable that can store length of array.

a.length returns the number of elements in the array a.

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]);
}
}

TWO DIMENSIONAL ARRAYS:


1. If an array has two sub scripts, then it is called as two dimensional array. These are otherwise called as
matrix arrays or table arrays.
2. These are used to organize in terms of rows and columns.
3. Each element in two dimensional array is identified by name of the array, its row index and its column
index.
0 1 2 3
0 a[0][0] a[0][1] a[0][2] a[0][3]
1 a[1][0] a[1][1] a[1][2] a[1][3]
2 a[2][0] a[2][1] a[2][2] a[2][3]
3 a[3][0] a[3][1] a[3][2] a[3][3]
CREATION OF 2-D ARRAY:

We can create a 2D array as follows.


datatype array-name[ ][ ];
or
datatype[ ][ ] array-name;

Example:
int a[ ][ ];
int[ ][ ] a;

Creating Memory Locations:

array-name = new datatype[row-size][column-size];


a=new int[3][3];
In the above example, the array a has given memory for 9 elements which are organized as 3 rows and 3
columns. The first element in the array will be a[0][0] and the last element a[2][2].

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.

ADT operations on list:


1. Create an empty list
2. Find: Locate the position of an object in a list.
List: 34, 23,12, 45, 29
Find(29)  5
3. Insert: Insert an object into a list.
Insert(x,3)  34, 23, x, 12,45, 29
4. PrintList: displaying all the elements in the list.
5. Remove: Delete an element from the list
Remove(12) 34,23,x,45,29
6. Find Kth element: Retrieve the element at Kth position

Differences Between Array and LinkedList:


ARRAY LINKED LIST
1. An array is a collection of elements having 1. Linked List is an ordered collection of
same data type with common name. elements which are connected by links or
2. In Array, elements can be accessed using index pointers.
or subscript value i.e., elements can be 2. In Linked List, elements can be accessed
accessed randomly. So array provides faster accesses sequentially and accessing element
random access. takes order of n O(n) times.
3. In Array, elements are stored in consecutive 3. In Linked List, elements can be stored at any
memory locations. available place as address of node is stored in
previous node.
4. Insertion & Deletion takes more time in array 4. Insertion & Deletions are fast and easy in
as elements are stored in consecutive memory linked list as only value of pointer is needed to
locations. change.
5. In Array memory is allocated at compile time 5. In Linked List memory is allocated at runtime
i.e., static memory allocation. i.e., Dynamic Memory Allocation.
6. Array can be single dimensional, two 6. Linked List can be single, double or circular
dimensional or multi dimensional. linked list.
7. In Array each element is independent, no 7. In Linked List location or address is stored in
connection with previous element or with its the link part of previous element or node.
location. 8. In Linked List, adjacency between the
8. In Array no pointers are used like linked list. elements are maintained using pointers or
So, no need of extra space in memory for links. So pointers are used for that extra
pointer. memory space is needed.

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

SINGLE LINKED LIST:


A single linked list is a linear data structure and is a linear arrangement of nodes in which each node
contains two parts, data part and reference part, where reference part points to the next node.

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:

1. Initially head = null and last = null


2. Item=10
3. Since, item != -1 create a new node called temp.

4. temp.data = 10 , temp.link = null

5. since head = null so head = last = temp.

6. item = 20
7. Since, item != -1 create a new node called temp.

8. temp.data = 20 , temp.link = null

9. since head != null so, last.link = temp and last = temp.

10. item=30
11. Since, item != -1 create a new node called temp.

12. temp.data = 30 , temp.link = null

13. since head != null last.link = temp and last = temp.


11 | P a g e
14. item = -1
15. since item = -1, we will stop the process.

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.

1. set temp = head

2. since temp!=null, 10 is visited


3. temp=temp.link

4. since temp!=null, 20 is visited.


5. Now temp=temp.link

6. Since temp!=null, 30 is visited.


7. Now temp=temp.link

8. Since temp!=null, 40 is visited.


9. Now temp=temp.link

12 | P a g e
10. Since temp=null, the process stops here.

Counting Number of Nodes in a Linked List:


Step-1 : set temp = head , count=0
Step-2 : while temp!=null
Step-2.1 : count=count+1
Step-2.2 : temp=temp.link
Step-3 : Exit

Implementation:
Let us consider the following linked list with four nodes.

1. set temp = head

2. since temp!=null, count=1.


3. temp=temp.link

4. since temp!=null, count=2.


5. Now temp=temp.link

6. Since temp!=null, count=3.


7. Now temp=temp.link

8. Since temp!=null, count=4.


9. Now temp=temp.link

10. Since temp=null, the process stops here.

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( )

Step-1: Create a new node called temp.


Step-2: Read a value into item.
Step-3: Insert temp.data=item
temp.link=null
Step-4: temp.link=head
head=temp
Step-5: Exit

Implementation:
Let us consider the following the list with four nodes.

1. Create a new node called “temp”

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:

Let us consider the following the list with four nodes.

1. create a new node called “nodex”.

2. item=50
3. nodex.data=item , nodex.link=null

4. temp=head

5. since temp!=null , temp1=temp and temp=temp.link

6. since temp!=null , temp1=temp and temp=temp.link

7. since temp!=null , temp1=temp and temp=temp.link

8. since temp!=null , temp1=temp and temp=temp.link

9. since temp=null , temp1.link=nodex , last = nodex.

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.

1. create a new node called “nodex”.

2. item=25
3. nodex.data=item and nodex.link=null

4. place=3
5. set i=1 and temp=head

6. since 1<3 , temp1=temp , temp=temp.link and i=i+1

16 | P a g e
7. since 2<3, temp1=temp , temp=temp.link and i=i+1

8. since 3<3 is false , the process stopped here.


9. temp1.link = nodex.

10. nodex.link = temp

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.

Deleting head node:


If the head node is deleted then the next node will be the head node of the list.
Algorithm: deleteHead( )
Step-1: head = head.link
Step-2: Exit

Implementation

Let us consider the following list with four nodes.

17 | P a g e
1. head = head.link

Deleting Last Node:


For deleting a last node, we need to traverse until finding last node.

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

Let us consider the following list with four nodes.

1. temp = head

2. since temp.link != null , temp1 = temp , temp = temp.link

3. since temp.link != null , temp1 = temp , temp = temp.link

4. since temp.link != null , temp1 = temp , temp = temp.link

5. since temp.link = null , loop stopped here.

18 | P a g e
6. temp1.link = null , last = temp1

Deleting a node in between any two nodes:


In order to delete a node, we need to traverse until the node by keep tracking two successive nodes.

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

Let us consider the following list with four nodes.

1. place = 3
2. i=1 and temp = head

3. since i < place , temp1 = temp , temp = temp.link , i=i+1 = 2

4. since i < place , temp1 = temp , temp = temp.link , i=i+1 = 3.

5. since 3 < 3 is false, loop stops here.


6. temp1.link = temp.link

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

4. since temp ! = null and temp.data ! = key (30) so temp = temp.link

5. since temp != null and temp.data != key (30) so temp = temp.link

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);

Program to demonstrate Single Linked List:

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.

Head Node2 Node3 Last


NULL 10 20 30 40 NULL

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.

OPERATIONS ON DOUBLE LINKED LIST:

Creating a double linked list

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

5. temp.data=10, temp.nlink=NULL, temp.plink=NULL

6. since head = last = NULL, then head = last = temp

7. item=20
8. since item!= -1, so
9. create a new node called temp

10. temp.data=20, temp.plink = NULL, temp.nlink = NULL

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

15. temp.data=30 ; temp.plink = NULL ; temp.nlink = NULL

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 A DOUBLE LINKED LIST

Traversing means visiting each and every node. A double linked list can be traversed in two ways. They are

1. forward direction – from head to last


2. backward direction – from last to head

Traverse in Forward Direction:

Algorithm: Traverse Forward( )


Step1: set temp = head
Step2: while temp != NULL
Step1: display temp.data
Step2: temp = temp.nlink
Step3: exit
Implementation:

1. let us consider the following list with four nodes.

2. set temp = head

3. since, temp != NULL so 10 is visited.


4. Set temp = temp.nlink

5. Since temp != NULL. So 20 is visited


6. Set temp = temp.nlink

7. Since temp != NULL. So 30 is visited


8. Set temp = temp.nlink

9. Since temp != NULL. So 40 is visited.


27 | P a g e
10. Set temp = temp.nlink
11. Since temp = NULL, The process is stopped.

Traverse in Backward Direction:

Algorithm: Traverse Backward( )


Step1: set temp=last
Step2: while temp != NULL
Step1: display temp.data
Step2: temp = temp.plink
Step3: exit
Implementation:

1. Let us consider the following list with 4 nodes.

2. Set temp = last

3. Since temp != NULL. So, 40 is visited.


4. Set temp = temp.plink

5. Since temp != NULL. So, 30 is visited


6. Set temp = temp.plink

7. Since, temp != NULL. So, 20 is visited


8. Set temp = temp.plink

9. Since temp != NULL. So, 10 is visited


10. Set temp = temp.plink
11. Since temp = NULL. The process is stopped.

INSERTING A NODE IN DOUBLE LINKED LIST:

The insertions can be done in the following three situations.

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( )

Step1: Create a new node called “temp”


Step2: Read a value into “item”
Step3: Insert, temp.data = item
temp.nlink = NULL
temp.plink = NULL
Step4: temp.nlink = head
head.plink = temp
head = temp
Step5: Exit

Implementation:
1. Let us consider the list with following 4 nodes.

2. Create a new node called temp.

3. Item = 5
4. temp.data= item ; temp.nlink = NULL ; temp.plink = NULL

5. temp.nlink = head ; head.plink = temp ; head = temp

Inserting at Last:

Algorithm: insertAtLast( )

Step1: Create a new node called “temp”.


Step2: Read a value into “item”
Step3: Insert, temp.data = item
temp.plink = NULL
temp.nlink = NULL
Step4: last.nlink = temp
temp.plink = last
last = temp
Step5: Exit

29 | P a g e
Implementation:
1. Let us consider the list with following 4 nodes.

2. Create a new node called temp.

3. Item = 50
4. temp.data= item ; temp.nlink = NULL ; temp.plink = NULL

5. temp.plink = last ; temp.nlink=NULL ; last = temp

Inserting between any two nodes: insertAtMiddle( )

Step1: Create a new node called “nodex”


Step2: Read a value into item
Step3: Insert nodex.data=item
nodex.plink=NULL
nodex.nlink=NULL
Step 4: Read place to insert into „place‟
Step 5: set i=1, temp=head
Step 6: while (i<place)
Step 6.1: temp 1 = temp
Step 6.2: temp = temp.nlink
Step 6.3: i=i+1
Step 7: temp1.nlink = nodex, nodex.plink = temp1.
Step8: nodex.nlink=temp, temp.plink = nodex
Step 9: Exit
Implementation:

1. Let us consider the following lists with four nodes.

2. Create a new node called “nodex”

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

7. a. since 1<3, so temp1 = temp, temp = temp.nlink i = i + 1

b. since 2<3 , so temp1 = temp , temp = temp.nlink i = i + 1

c. since 3<3 is false , so the process stopped.

8. temp1.nlink = nodex , nodex.plink = temp1

9. nodex.nlink = temp , temp.plink = nodex

Deleting a Node in a Double Linked List:


31 | P a g e
The deletion of a node can be done in the following 3 situations.

i. Deleting a head node


ii. Deleting a last node
iii. Deleting a node in between two nodes.

Deleting a Head Node:

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( )

Step 1: Set head = head.nlink


Step 2: set head.plink = NULL.
Step 3: Exit
Implementation:

i. Let us consider the following list with four nodes.

ii. head = head.nlink

iii. head = head.plink = NULL

Deleting a last Node:

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( )

Step 1: set last = last.plink


Step 2: last.nlink = NULL
Step 3: Exit
Implementation:
i. let us consider the following list of 4 nodes.

32 | P a g e
ii. last = last.plink

iii. last.nlink = NULL

Deleting a node between any two nodes:

In order to delete a node, we need to traverse until the node by tracking two successive nodes.

Algorithm: deleteMiddle( )

Step 1: Read place to delete into “place”.


Step 2: set i=1, temp = head
Step 3: while (I < = place-1)
Step 3.1: temp1 = temp
Step 3.2: temp = temp.nlink
Step 3.3: i = i + 1
Step 4: temp = temp.nlink
Step 5: temp1.nlink = temp
Step 6: temp.plink = temp1
Step 7: Exit
Implementation:

I. Let us consider the following list with 4 nodes.

II. Place = 3
III. i = 1 , temp = head

IV. a. since, 1<=2. So, temp1 = temp , temp = temp.nlink , i = i + 1

33 | P a g e
b. since 2<=2, so, temp1 = temp , temp = temp.nlink , i=i+1

c. since 3<=2 is false, the loops stops here.

V. temp = temp.nlink

VI. temp1.nlink = temp , temp.plink = temp1.

CIRCULAR LINKED LIST:

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.

The following is the circular linked list with four nodes.

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

 sparse triangular matrix


 sparse tridiagonal matrix

Sparse triangular Matrix:

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.

Stacks can be implemented by using following two ways:

1. Stacks using arrays.


2. Stacks using linked list.

STACK USING ARRAYS: The stacks are very easily implemented with the help of arrays.

Algorithm: push( ) Operation

[ initially top = - 1 , MaxSize = 10 ]


Step-1 : [ check for overflow ]
if(top+1>=MaxSize)
Display “OVER FLOW”
else
top = top+1
Read a value into item
Stack[top] = item
Step-2 : Exit

37 | P a g e
Implementation:

Initially, top = - 1 and MaxxSize = 5

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.

Algorithm: pop( ) operation

Step-1 : [ check for underflow ]


if( top = = - 1)
Display “underflow”
else
item = stack[ top ]
top = top – 1;
Display “ popped item is “+item
Step-2 : Exit

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

Step-1: if(top = = -1)


Display “Stack is empty”
else
Step-1.1: set i = top
Step-1.2: while ( i>=0 )
a) Display stack [ i ]
b) i = i -1
step-2: Exit

Implementation:
1. Consider the following stack. And set i=top.

2. Since i != -1display a[ i ] that is 50 and set i=i-1

39 | P a g e
3. Since i != -1display a[ i ] that is 40 and set i=i-1

4. Since i != -1display a[ i ] that is 30 and set i=i-1

5. Since i != -1display a[ i ] that is 20 and set i=i-1

6. Since i != -1 display a[ i ] that is 10 and set i=i-1

7. Since i = -1 display “No more elements in stack”.

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

4. since top==null set top=temp.

5. Item=20, create a node temp and set temp.data=20, temp.link=null.

6. Set temp.link=top and top=temp.

7. Item=30, create a node temp and set temp.data=30, temp.link=null

8. Set temp.link=top and top=temp

42 | P a g e
Algorithm: pop( ) operation

Step-1: [ check for underflow ]


if ( top = = null )
display “Stack Underflow”
else
item=top.data
display “deleted item is” item
top=top.link
step-2: Exit

Implementation:
Consider the following stack as Example.

1. Since top != null , item=top.data =30 and top=top.link

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.

1. Since top != null, set temp=top.

2. Since temp != null Display temp.data that is 30 and temp=temp.link.

3. Since temp != null Display temp.data that is 20 and temp=temp.link

4. Since temp != null display temp.data that is 10 and temp=temp.link.


5. Since temp = null stop process.

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.

Algorithm to convert InFix expression into PostFix expression:


Input: An infix string “Q”
Output: A postfix string “P”

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.

Algorithm to Evaluate Post fix expression:

Input: A Post Fix expression “P”


Output: Result of Postfix 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/+

Now the Post fix expression is P: 3,12,3,/,2,+,*,15,3/+

SNO SYMBOL STACK


1 3 3
2 12 3,12
3 3 3,12,3
4 / 3,4
5 2 3,4,2
6 + 3,6
7 * 18
8 15 18,15
9 3 18,15,3
10 / 18,5
11 + 23

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.

EnQueue: The insertion operation is called EnQueue(ENQ).


DeQueue: The deletion operation is called DeQueue(DNQ).
Traverse: Visiting each and every element of a Queue is called “Traversing”.

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.

Queues can be implemented in two ways.


1. Queues using Arrays.
2. Queues using LinkedList.

QUEUES USING ARRAYS:

A Queue can be easily implemented with the help of arrays.


Algorithm: Insertion Operation:

Initially front = rear = -1


Step-1: [ check for Overflow ]
If( rear + 1 >= maxsize )
Display “Queue Overflow”
Else
Step-1.1: Read an element into item.
Step-1.2: if(rear = = -1) then
Rear = front = 0
Else
Rear = rear + 1
Step-1.3: a[rear] = item
Step-2: Exit

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

6. Since, (rear+1)=1>=5 is false


7. Item=20
8. Since rear != -1 rear = rear + 1, Q[rear]=20

9. Since, (rear+1)=2>=5 is false


10. Item=30
11. Since rear != -1 rear = rear + 1, Q[rear]=30

12. Since, (rear+1)=3>=5 is false


13. Item=40
14. Since rear != -1 rear = rear + 1, Q[rear]=40

15. Since, (rear+1)=4>=5 is false


16. Item=50
17. Since rear != -1 rear = rear + 1, Q[rear]=50

18. Since, (rear+1)=5>=5 is true, display “Queue Overflow”.

48 | P a g e
Algorithm: Deletion Operation:

Step-1: [ check for underflow ]


If( front = -1 or front > rear )
Display “ Queue is underflow”
Else
Step-1.1: item=Q[front]
Step-1.2: front=front+1
Step-1.3: Display :Deleted item is” + item
Step-2: Exit

Implementation:
1. Let us consider the following Queue with maxzise=5.

2. Since front != -1 and front>rear is false


3. Item=Q[front]=10 and front=front+1=1

Display “deleted element is 10”


4. Since front != -1 and front>rear is false
5. Item=Q[front]=20 and front=front+1=2

Display “deleted element is 20”


6. Since front != -1 and front>rear is false
7. Item=Q[front]=30 and front=front+1=3

Display “deleted element is 30”


8. Since front != -1 and front>rear is false
9. Item=Q[front]=40 and front=front+1=4

Display “deleted element is 40”


49 | P a g e
10. Since front != -1 and front>rear is false
11. Item=Q[front]=50 and front=front+1=5

Display “deleted element is 50”


12. Since front != -1 and front>rear is true display “ Queue is underflow”.

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.

2. Since i<=rear is true display Q[ i ] =10 and i=i+1=1

3. Since i<=rear is true display Q[ i ] =20 and i=i+1=2

4. Since i<=rear is true display Q[ i ] =30 and i=i+1=3

5. Since i<=rear is true display Q[ i ] =40 and i=i+1=4

50 | P a g e
6. Since i<=rear is true display Q[ i ] =50 and i=i+1=5

7. Since i<=rear is false stop process.

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);

}
}

Queue Using LinkedList:


While representing queues using list we require two nodes which are front and rear.
Algorithm: Insertion:

[ Initially front = null and rear = 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 front = = null then
front = rear = temp
else
rear.link = temp
rear = temp
[ Repeat the process until item = = -1 ]
Step-3: Exit

Algorithm: Deletion:

Step-1: [ check for underflow ]


If(front = = null )
Display “Queue is underflow”
Else
Item=front.data
Front=front.link
Repeat this until front=null.
Step-2: Exit

Algorithm: Traversing:

Step-1: set temp=front


Step-2: while(temp != null)
Display temp.data
Temp=temp.link
Step-3: Exit

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( )

9. Insertion( ) 10. Insertion( )


Item=60 Item=70

12. Insertion( ) The next iteration of rear is


11. Insertion( )
Item=90 equal to front. So, the Queue is
Item=80
overflow.

Algorithm: Insertion( )

Step-1: [ check for overflow ]


If((rear+1) % max-size = = front) then
Display “ Queue is Overflow”
Else
Step-1.1: read a value into item
Step-1.2: if( rear = = -1) then
55 | P a g e
rear = front = 0
else
rear = ( rear + 1 ) % max-size
Step-1.3: Q[rear] = item
Step-2: Exit

Algorithm: Deletion( )

Step-1: [ check for underflow ]


If( front = = -1 ) then
Display “Queue is underflow”
Else
Step-1.1: item=Q[front]
Step-1.2: if( front = = rear ) then
Front = rear = -1
Else
Front = (front+1)%max-size
Step-1.3: display “element deleted”+item
Step-2: Exit
Algorithm: Traversing( )

Step-1: set i=front


Step-2: while ( i != (rear + 1)%max-size )
Step2.1: display Q[ i ]
Step2.2: i=(i+1)%max-size
Step-3: Exit

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);
}
}

Double Ended Queues


A Double Ended Queue is an abstract data structure that implements a Queue in which insertions and
deletions will be done either at the front end or at the rear end pf the Queue. The operations that can be
performed on double ended queue are
1. Insert an item from front end
2. Insert an item from rear end
3. Delete an item from front end
4. Delete an item from rear end
5. Display the elements of Queue

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.

“A tree T(n), is an unordered collection of data items distributed non-linearly such as

i. One data item acts as root for others.


ii. There should exist one path between any pairs of nodes. (It doesn‟t form any cycle).

Terminology:

Root  A node with no parent nodes is called “root node”.

Leaf  A node with no children is called leaf node.

Siblings  Children of same parents is called siblings.

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”.

The height of the above tree is 3.

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.

3  Complete Binary Tree (Balanced Tree):

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.

The height if left sub-tree is 2 and right sub-tree is 3.

So, it is called complete binary 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:

The In-Order traversal of the above tree is as follows:

HCBDAFEGIJ
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

Recursive Algorithm for Pre-Order Traversal:


Step-1: visit root (root.data)
Step-2: visit left sub-tree (root.lchild)
Step-3: visit right sub-tree (root.rchild)
Step-4:exit.

62 | P a g e
Implementation:

The pre-order traversal of the above tree is as follows:

ABCHDEFGIJ
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:

The post-order traversal of the above tree is as follows:

HCDBFJIGEA
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.

BINARY SEARCH TREE (BST):


A Binary tree is said to be binary search tree if the nodes of the left sub-tree of the root node are less
than root node and the nodes of the right sub-tree of the root node are greater than or equal to the root node.
Let us consider the following numbers to be stored into a binary search tree.

35, 14, 10, 25, 40, 50, 45, 65

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

Operations On Binary Search Tree:


The following are some of the operations that can be performed on trees.
1. Creating a binary search tree
2. Inserting a node into BST
3. Deleting a node from BST
a. Deleting a leaf node
b. Deleting a node with one Child

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

Creating and inserting a node into BST:


Step-1: initially root=null
Step-2: create a new node called “nodex”
Step-3: insert nodex.data=item
nodex.lchild=null
nodex.rchild=null
Step-4: if (root = = null) then
root = nodex
else
Step-5: set temp=root
Step-6: while(true)
6.1 - if (nodex.data<temp.data) then goto step 6.1.1 otherwise goto 6.2
6.1.1 - if (temp.lchild = = null) then
temp.lchild=nodex
else
temp=temp.lchild
6.2 - if (temp.rchild = = null ) then
temp.rchild= nodex
else
temp=temp.rchild
Step-7: Exit

Implementation:
1. Initially root=null, item=47
2. Create a new node called nodex

3. nodex.data=item(47), nodex.lchild=null, nodex.rchild=null.

4. since root=null set root=nodex.

5. Read item=39
6. Create a new node called nodex

7. nodex.data=item(39), nodex.lchild=null, nodex.rchild=null.


67 | P a g e
8. since root != null set temp = root
9. since nodex.data < temp.data set temp.lchild=nodex.

10. Read item=56


11. Create a new node called nodex

12. nodex.data=item(56), nodex.lchild=null, nodex.rchild=null.

13. since root != null set temp = root

14. since nodex.data > temp.data and temp.rchild=null set temp.rchild=nodex

15. Read item=42


16. Create a new node called nodex

17. nodex.data=item(42), nodex.lchild=null, nodex.rchild=null.

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.

20. since nodex.data > temp.data and temp.rchild=null set temp.rchild=nodex.

21. Read item=53


22. Create a new node called nodex

23. nodex.data=item(53), nodex.lchild=null, nodex.rchild=null.

24. since root != null set temp=root.


25. Since nodex.data > temp.data and temp.rchild!=null set temp=temp.rchild.

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);
}
}

Deleting a node from Binary Search Tree:


The deletion of a node from binary search tree can be done in the following cases.
1. Deleting a leaf node
2. Deleting a node with one child
3. Deleting a node with both child
In-order to delete a node from a binary search tree, we need to traverse until that is reached.
Deleting a leaf Node:

72 | P a g e
To delete a node temp1 which is left-child to temp, we need to set temp.lchild=null.

Deleting a node with one child:

To delete a node temp which is having one child, we need to set temp1.rchild=temp.rchild, then

Deleting a node with two childs:


Find the minimum element in the right most sub tree of the node to be removed. Let us consider the following
example:

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.

Threaded Binary Tree (TBT):


We know that a binary tree is represented either by using arrays or by using linked list.
1. When a binary tree is represented is by using linked list, if any node is not having a child, we use null
reference in that position.
2. In any binary tree there are more number of null references than actual references, it wastes lot of
storage space.

To convert a binary tree into threaded binary tree


1. Keep the null values as it is in the left-child reference of left most node and right-child of right most
node.
2. Write the in-order traversal of binary tree.
3. If the null reference is from left child then point it to its in-order predecessor and and point in-order
successor in case of right child.

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.

Now the in-order traversal of the above tree is


DBEACF
Now remove null values and replace them with in-order predecessor in case of left-child and with in-order
successor in case of right-child.

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:

Field-1 - reference of left child


Field-2 - left flag i.e., 0 or 1
Field-3 - data in that node
Field-4 - right flag i.e., 0 or 1
Field-5 - reference of right child
 In fileds2 and 4 the value 0 represents left/right child references to its parent/ancestor node.
 In fields2 and 4 the value 1 represents left/right child references to its direct child node.
And we create a temporary node which does not contain any data and it is referenced by left-child of left most
node and right-child of right most child. The left child reference of temporary node points to root node and the
right child references to itself.

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.

4. Directed graph or Digraph:


A graph G(V,E) is said to be digraph, if the directions are specified for all 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.

Representation of Graph in Memory:


A graph in memory is represented in two ways.
1. Adjacency Matrix
2. Adjacent List

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.

Graph Traversing Techniques:


There are two different kinds of graph traversing techniques, those are
1. Depth First Search (DFS)
2. Breadth First Search (BFS)

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.

Vertex set V= { A,B,C, D, E, F,G}


Status set S = { 0, 0, 0, 0, 0, 0, 0 } and stack is empty.
Let the chosen vertex be „A‟
Status set S = { 1, 0, 0, 0, 0, 0, 0 }
Pop the top element from the stack while
pushing all of its neighbors into stack and
Status set S = { 2, 1, 0, 0, 0, 0, 1 }
update the status of popped element to 2 and
pushed elements to 1. So A is visited.
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, 1, 0, 0, 1, 2 }
pushed elements to 1. So G is visited.

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
pushed elements to 1. So C is visited. Status set S = { 2, 1, 2, 1, 1, 1, 2 }

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.

Pop the top element from the stack while


pushing all of its neighbors into stack and
Status set S = { 2, 1, 2, 2, 2, 1, 2 }
update the status of popped element to 2 and
pushed elements to 1. So D is visited.
Pop the top element from the stack while
pushing all of its neighbors into stack and
Status set S = { 2, 1, 2, 2, 2, 2, 2 }
update the status of popped element to 2 and
pushed elements to 1. So F is visited.
Pop the top element from the stack while
pushing all of its neighbors into stack and
Status set S = { 2, 2, 2, 2, 2, 2, 2 }
update the status of popped element to 2 and
pushed elements to 1. So B is visited.
Now the stack is empty and status set contains status 2 for all the vertices. So the process stopped here. Now the
DFS result the following sequence of vertices.

AGCEDFB
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 }

Delete the front element from the Queue


while pushing all of its neighbors into
Queue at rear whose status is „0‟ and Status set S = { 2, 1, 0, 0, 0, 0, 1 }
update the status of deleted element to 2
and inserted elements to 1. So A is visited.
Delete the front element from the Queue
while pushing all of its neighbors into
Queue at rear whose status is „0‟ and Status set S = { 2, 2, 1, 0, 0, 1, 1 }
update the status of deleted element to 2
and inserted elements to 1. So B is visited.
Delete the front element from the Queue
while pushing all of its neighbors into
Queue at rear whose status is „0‟ and Status set S = { 2, 2, 1, 0, 0, 1, 2 }
update the status of deleted element to 2
and inserted elements to 1. So G is visited.
Delete the front element from the Queue
while pushing all of its neighbors into
Queue at rear whose status is „0‟ and Status set S = { 2, 2, 2, 1, 1, 1, 2 }
update the status of deleted element to 2
and inserted elements to 1. So C is visited.
Delete the front element from the Queue
while pushing all of its neighbors into
Queue at rear whose status is „0‟ and Status set S = { 2, 2, 2, 1, 1, 2, 2 }
update the status of deleted element to 2
and inserted elements to 1. So F is visited.
Delete the front element from the Queue
while pushing all of its neighbors into
Queue at rear whose status is „0‟ and Status set S = { 2, 2, 2, 2, 1, 2, 2 }
update the status of deleted element to 2
and inserted elements to 1. So D is visited.
Delete the front element from the Queue
while pushing all of its neighbors into
Queue at rear whose status is „0‟ and Status set S = { 2, 2, 2, 2, 2, 2, 2 }
update the status of deleted element to 2
and inserted elements to 1. So E is visited.

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.
AGCEDFB
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.

The spanning trees for the above graph are

Minimum Spanning Trees:


For a weighted graph, the spanning tree which is formed with all the vertices of the graph whose total
cost is minimum among all the other spanning trees is called “minimal spanning tree”. Obtaining a minimum
cost spanning tree involves so much of work. In-order to simplify this process, two algorithms are introduced
they are
1. Kruskal‟s algorithm
2. Prim‟s algorithm
The DFS and BFS traversals result in a spanning tree but it is not guaranteed to be a minimum spanning tree.
KRUSKAL‟S ALGORITHM:
The algorithm was introduced by a mathematician J.B.Kruskal.
Algorithm:
Step-1: Initialize all the vertices with no edges.
Step-2: Maintain a list of edges I an increasing order of weights.
Step-3: Choose edges from list one by one and add it to the tree if it doesn‟t form a cycle.
Step-4: Repeat step 3 until (n-1) edges are added to the tree.

84 | P a g e
Implementation:
Let us consider the following weighted graph with 6 vertices.

1. Initialize all the vertices with no edges.

Edge Weight Status


BE 1 0
AB 2 0
DF 3 0
AE 3 0
AF 4 0
CF 4 0
BD 5 0
CD 6 0
ED 6 0
BC 7 0

2. Least cost edge is BE.


Edge Weight Status
BE 1 1(select)
AB 2 0
DF 3 0
AE 3 0
AF 4 0
CF 4 0
BD 5 0
CD 6 0
ED 6 0
BC 7 0

3. Next least cost edge is AB.

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

4. The next least cost edge is DF.

Edge Weight Status


BE 1 1(select)
AB 2 1(select)
DF 3 1(select)
AE 3 0
AF 4 0
CF 4 0
BD 5 0
CD 6 0
ED 6 0
BC 7 0

5. Next least cost edge is AE. But it forms a cycle. So it is rejected.


6. The next least cost edge is AF.

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 0
BD 5 0
CD 6 0
ED 6 0
BC 7 0

7. Next least cost edge is CF.

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.

2. Let the chosen vertex be A. so set S={A}.


3. The least among AB, AE, AF is AB. So S={A, B}.

4. The least among AE,AF,BC,BD,BE is BE. So set S={A, B, E}.

5. Remove the edge AE because it forms a cycle.


6. Least among the AF,BC,BD,ED is AF. So set S={A, B, E, F}

88 | P a g e
7. The least among BD,BC,ED,FC,FD is FD. So set S={A,B,E,F,D}

8. The least among BD,BD,ED,FC is FC. So set S={A,B,E,F,D,C}.

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.

First we will split the list into two parts as follows.


First element will be considered as sorted list and all the remaining will be considered as unsorted list.

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.

There are no more elements left to compare. So 7 is placed at a[0].


Time Complexity:
Best Case : O(n)
Worst Case : O(n2)
Average Case : O(nlogn)

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:

Step-1: Read a list of elements into an array of size n


Step-2: Divide the unsorted list into two sub-lists of about half the size until the sub-list contains single element.
Step-3: Sort each sub-list recursively by reapplying merge sort
Step-4: Merge the two lists into one sorted list until the final list contains n elements.

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

You might also like