Data Structures

You might also like

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

PRAGATI WOMEN’S DEGREE COLLEGE II BSC

DATA STRUCTURES
Unit-1: Concept of Abstract Data Type (ADT’S)
Q.1. Explain the DataType in DataStructures.
Ans: Data Type:
Data type is a way to classify various types of data such as integer, string, etc.
which determines the values that can be used with the corresponding type of data,
the type of operations that can be performed on the corresponding type of data.
There are two data types −

 Built-in Data Type

 Derived Data Type


Built-in Data Type:
Those data types for which a language has built-in support are known as Built-in
Data types. For example, most of the languages provide the following built-in data
types.

 Integers

 Boolean (true, false)

 Floating (Decimal numbers)

 Character and Strings


Derived Data Type:
Those data types which are implementation independent as they can be
implemented in one or the other way are known as derived data types. These data
types are normally built by the combination of primary or built-in data types and
associated operations on them. For example −

 List

 Array

 Stack
1
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC

 Queue

Q.2. Explain the DataStructure and Characteristics, Need for data structure.

Ans: Data Structures:

A data structure is a specialized format for organizing and


storing data. General data structure types include the array, the file, the record, the
table, the tree, and so on. Any data structure is designed to organize data

Data Structure is a systematic way to organize data in order to use it efficiently.


Following terms are the foundation terms of a data structure.

 Interface − each data structure has an interface. Interface represents the set
of operations that a data structure supports. An interface only provides the
list of supported operations, type of parameters they can accept and return
type of these operations.

 Implementation − Implementation provides the internal representation of a


data structure. Implementation also provides the definition of the algorithms
used in the operations of the data structure.

Fig:Data Structure

2
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC

Characteristics of a Data Structure:


 Correctness − Data structure implementation should implement its
interface correctly.

 Time Complexity − Running time or the execution time of operations of


data structure must be as small as possible.

 Space Complexity − Memory usage of a data structure operation should be


as little as possible.

Need for Data Structure:


As applications are getting complex and data rich, there are three common
problems that applications face now-a-days.

 Data Search − Consider an inventory of 1 million(10 6) items of a store. If


the application is to search an item, it has to search an item in 1 million(10 6)
items every time slowing down the search. As data grows, search will
become slower.

 Processor speed − Processor speed although being very high, falls limited
if the data grows to billion records.

 Multiple requests − As thousands of users can search data simultaneously


on a web server, even the fast server fails while searching the data.

Q.3. Explain Primitive and non-Primitive Data structures.

(or)

Explain Linear and Non-Linear Datastructures.

Ans: Primitive and non-Primitive Data structures:


3
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC

The primitive data structures are the basic data types that are available in
most of the programming languages. The primitive data types are used to
represent single values. Integer: This is used to represent a number without
decimal point. Float and Double: This is used to represent a number with decimal
point.

The Non-primitive data structures we also have some complex Data


Structures, which are used to store large and connected data. Some examples
of Abstract Data Structure are:
1. Linked List
2. Tree
3. Graph
4. Stack,
5. Queue etc.

Fig: Primitive and Non-Primitive Data Structure

Linear and Non-Linear Data Structures:

Linear data structures are in which all the data are arranged in sequence
manner. A linear data structure is any data structure that must be traversed
linearly.

For example: linked list, stack, and queue.


4
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC

Non linear data structures are in which all the data are arranged in
random manner.

For example: trees, graphs.

Fig: Linear &Non Linear Data Structures

Linear List:

The elements are ordered within the linear list in


a linear sequence. Linear lists are usually simply denoted as lists. Unlike an array,
a list is a data structure allowing insertion and deletion of elements at an arbitrary
position of the sequence. ... So they are a dynamic data structure.

ADT:

An abstract data type (ADT) is a mathematical model for data types where
a data type is defined by its behavior (semantics) from the point of view of a user
of the data, specifically in terms of possible values, possible operations on data of
this type, and the behavior of these operations.

Abstract Data Type is a definition of


new type, describes its properties and operations. Data Structure is an
implementation of ADT. Many ADT can be implemented as the same Data
Structure.

The abstract data type is also alternatively termed user-defined data type
is known in ‘c’.If a programmer wants to process a date then an abstract data

5
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC

type ,say date, has to be devised and various operations. For example suppose we
want to process a dates of form DD/MM/YY.

Programmer’s should decide how to store the data, what amount of


memory will be needed to represent a value of Date.

Array Representation:

Array is a container which can hold a fix number of items and these items should
be of the same type. Most of the data structures make use of arrays to implement
their algorithms.

 Element − Each item stored in an array is called an element.

 Index − Each location of an element in an array has a numerical index,


which is used to identify the element.

Arrays can be declared in various ways in different languages. For illustration,


let's take C array declaration.

Fig: Array Representation


As per the above illustration, following are the important points to be considered.

 Index starts with 0.

 Array length is 8 which means it can store 8 elements.

 Each element can be accessed via its index. For example, we can fetch an
element at index 6 as 9.
6
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC

Basic Operations
Following are the basic operations supported by an array.

 Traverse − print all the array elements one by one.

 Insertion − Adds an element at the given index.

 Deletion − Deletes an element at the given index.

 Search − Searches an element using the given index or by the value.

 Update − Updates an element at the given index.

Linked Representation:
A linked-list is a sequence of data structures which are
connected together via links.

Linked List is a sequence of links which contains items.


Each link contains a connection to another link. Linked list the second most used
data structure after array. Following are important terms to understand the
concepts of Linked List.

 Link − Each Link of a linked list can store a data called an element.

 Next − Each Link of a linked list contain a link to next link called Next.

 Linked List − A Linked List contains the connection link to the first Link
called First.

Linked List Representation:

Fig: Linked List Representation

7
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC

As per above shown illustration, following are the important points to be


considered.

 Linked List contains a link element called first.

 Each Link carries a data field(s) and a Link Field called next.

 Each Link is linked with its next link using its next link.

 Last Link carries a Link as null to mark the end of the list.

Stack:

A stack is a limited access data structure - elements can be added and


removed from the stack only at the top. Push adds an item to the top of
the stack, pop removes the item from the top.

Stack
Queue:
Queue is an abstract data structure, somewhat similar to Stacks. Unlike
stacks, a queue is open at both its ends.
One end is always used to insert data(enqueue)
and the other is used to remove data(dequeue). Queue follows First-In-First-Out
methodology, i.e., the data item stored first will be accessed first.

8
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC

Fig: Queue

Tree:

A tree is a widely used abstract data type (ADT)—or data


structure implementing this ADT—that simulates a hierarchical tree structure,
with a root value and subtrees of children with a parent node, represented as a set
of linked nodes.

Tree

Graph:

A graph is a pictorial representation of a set of objects where some pairs of


objects are connected by links. The interconnected objects are represented by
points termed as vertices, and the links that connect the vertices are called edges.

Formally, a graph is a pair of sets (V, E), where V is the set of vertices
and E is the set of edges, connecting the pairs of vertices. Take a look at the
following graph

9
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC

Fig: Graph

In the above graph,

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

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

Sets:

A set is an abstract data type that can store certain values, without any
particular order, and no repeated values. It is a computer implementation of the
mathematical concept of a finite set. ... An abstract data structure is a collection, or
aggregate, of data.

Table:

A table is a data structure that organizes information into rows and columns. It
can be used to both store and display data in a structured format. For example,
databases store data in tables so that information can be quickly accessed from
specific rows.

Q.4. Explain the Types and operations of linked list

Ans: Types of Linked List:


Following are the various types of linked list.

 Single Linked List − Item Navigation is forward only.

10
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC

 Doubly Linked List − Items can be navigated forward and backward way.

 Circular Linked List − Last item contains link of the first element as next
and first element has link to last element as prev.

Operations of Linked List:


Following are the basic operations supported by a list.

 Insertion − add an element at the beginning of the list.

 Deletion − delete an element at the beginning of the list.

 Display − displaying complete list.

 Search − search an element using given key.

 Delete − delete an element using given key.

Insertion Operation:
Insertion is a three step process

 Create a new Link with provided data.

 Point New Link to old First Link.

 Point First Link to this New Link.

11
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC

Fig: Insert Operation

Deletion Operation:
Deletion is a two step process

 Get the Link pointed by First Link as Temp Link.

 Point First Link to Temp Link's Next Link.

12
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC

Fig: Delete operation

Advanced Operations:
Following are the advanced operations specified for a list.

 Sort − sorting a list based on a particular order.

 Reverse − reversing a linked list.

Single Linked List:

Singly Linked Lists are a type of data structure. It is a type


of list. In a singly linked list each node in the list stores the contents of the node
and a pointer or reference to the next node in the list. It does not store any pointer
or reference to the previous node.

Fig: Singed Linked List

Operations that can be performed on singly linked lists include insertion, deletion

and traversal.

13
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC

Insertion:

In the Single Linked List insertion operation can be performed by three ways

1. Inserting at Beginning of the list

2. Inserting at End of the list

3. Inserting at Specific Location of the list

Fig: Insertion

Fig: Insertion

Deletion:

In the Single Linked List insertion operation can be performed by three ways

1. Deleting from Beginning of the list

2. Deleting from End of the list

3. Deleting a Specific node

14
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC

Fig: Deletion Operation

Advantages:

1. Singly linked list is probably the easiest data structure to implement.


2. Insertion and deletion of element can be done easily.

3. Insertion and deletion of elements doesn't require movement of all elements


when compared to an array.
4. Requires less memory when compared to doubly, circular or doubly circular
linked list.

5. Can allocate or deallocate memory easily when required during its


execution.

Double Linked List:

A doubly linked list is a linked data structure that consists of a set of


sequentially linked records called nodes. Each node contains two fields, called
links, That are references to the previous and to the next node in the sequence of
nodes.

 Link − each link of a linked list can store a data called an element.

 Next − each link of a linked list contains a link to the next link called Next.

 Prev − each link of a linked list contains a link to the previous link called
Prev.

15
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC

 Linked List − A Linked List contains the connection link to the first link
called First and to the last link called Last.

Fig: Double Linked List

Applications:

1. Doubly linked list can be used in navigation systems where both front and
back navigation is required.
2. It is used by browsers to implement backward and forward navigation of
visited web pages i.e. back and forward button.

3. It is also used by various applications to implement Undo and Redo


functionality.
4. It can also be used to represent deck of cards in games.
[[

5. It is also used to represent various states of a game.


Circular Linked List:

Circular Linked List is a variation of Linked list in which the


first element points to the last element and the last element points to the first
element. Both Singly Linked List and Doubly Linked List can be made into a
circular linked list.

In the circular linked list we can insert elements anywhere in the list

16
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC

Fig: Circular Linked List

Applications:

Any node can be a starting point. We can traverse the whole list by starting from
any point

 The real life application where the circular linked list is used is our Personal
Computers, where multiple applications are running.

 All the running applications are kept in a circular linked list and the OS gives a
fixed time slot to all for running. The Operating System keeps on iterating over
the linked list until all the applications are completed.

 Another example can be Multiplayer games. All the Players are kept in a
Circular Linked List and the pointer keeps on moving forward as a player's
chance ends.

 Circular Linked List can also be used to create Circular Queue. In a Queue we
have to keep two pointers, FRONT and REAR in memory all the time, where as
in Circular Linked List, only one pointer is required.

Double Linked list Operations:

 Insertion − Adds an element at the beginning of the list.

 Deletion − Deletes an element at the beginning of the list.

 Insert Last − Adds an element at the end of the list.


17
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC

 Delete Last − Deletes an element from the end of the list.

 Insert After − Adds an element after an item of the list.

 Delete − Deletes an element from the list using the key.

 Display forward − Displays the complete list in a forward manner.

 Display backward − Displays the complete list in a backward manner.

Q.5.What is Sparse Matrix explain with example.

Ans: Sparse Matrix:

A Matrix can be defined as 2-Dimentional array. Any array with


m-columns and n-rows represents a m x n matrix. Which a matrix contain more
number of zero values than non-zero values. Such matrix is known as Sparse
Matrix.

Sparse Matrix contain very few Non-zero values

When a Sparse Matrix is represented with 2-dimentional array, we waste lot of


space to represent to that matrix. For example consider a matrix of size 100 x 100
containing only 10 non-zero elements. In this matrix, only 10 spaces are filled with
non-zero values and remaining spaces of matrix are filled with zero.

Example of Sparse Matrix:

Types of Sparse Matrix:

1.Triangular Matrices:

Lower: Lower-left

Lower-right

Upper: Upper-left
18
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC

Upper-right

2.Band Matrices:

1) Diagonal

2)Trigonal 3)αβ-Band

Unit-2: Stacks & Queues

Stack:

Stack is an ordered list of similar data type. Stack is a LIFO structure. (Last
in First out). push () function is used to insert new elements into the Stack and
pop() is used to delete an element from the stack. Both insertion and deletion are
allowed at only one end of Stack called Top.

19
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC

Fig: Stack

ADT:

A stack is an abstract data type that serves as a collection of elements, with


two principal operations: push, which adds an element to the collection, and pop,
which removes the most recently added element that was not yet removed. ... The
pop operation removes an item from the top of the stack.

Stack ADT

Basic Operations
Stack operations may involve initializing the stack, using it and then de-
initializing it. Apart from these basic stuffs, a stack is used for the following two
primary operations −

 push() − Pushing (storing) an element on the stack.

20
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC

 pop() − Removing (accessing) an element from the stack.

When data is PUSHed onto stack.

To use a stack efficiently, we need to check the status of stack as well. For the
same purpose, the following functionality is added to stacks −

 peek() − get the top data element of the stack, without removing it.

 isFull() − check if stack is full.

 isEmpty() − check if stack is empty.

At all times, we maintain a pointer to the last PUSH data on the stack. As this
pointer always represents the top of the stack, hence named top. The toppointer
provides top value of the stack without actually removing it.

Push Operation
The process of putting a new data element onto stack is known as a Push
Operation. Push operation involves a series of steps −

 Step 1 − Checks if the stack is full.

 Step 2 − If the stack is full, produces an error and exit.

 Step 3 − If the stack is not full, increments top to point next empty space.

 Step 4 − Adds data element to the stack location, where top is pointing.

 Step 5 − Returns success.

If the linked list is used to implement the stack, then in step 3, we need to allocate
space dynamically.

Algorithm for PUSH Operation


A simple algorithm for Push operation can be derived as follows −

begin procedure push: stack, data

21
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC

if stack is full
return null
endif

top ← top + 1

stack[top] ← data

end procedure

Example:

void push(int data) {


if(!isFull()) {
top = top + 1;
stack[top] = data;
} else {
printf("Could not insert data, Stack is full.\n");
}
}

Pop Operation
Accessing the content while removing it from the stack, is known as a Pop
Operation. In an array implementation of pop() operation, the data element is not
actually removed, instead top is decremented to a lower position in the stack to
point to the next value. But in linked-list implementation, pop() actually removes
data element and deallocates memory space.

22
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC

A Pop operation may involve the following steps −

 Step 1 − Checks if the stack is empty.

 Step 2 − If the stack is empty, produces an error and exit.

 Step 3 − If the stack is not empty, accesses the data element at whichtop is
pointing.

 Step 4 − Decreases the value of top by 1.

 Step 5 − Returns success.

Algorithm for Pop Operation


A simple algorithm for Pop operation can be derived as follows −

begin procedure pop: stack

if stack is empty
return null
endif

data ← stack[top]

top ← top - 1

return data

end procedure

Implementation of this algorithm in C, is as follows −


23
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC

Example

int pop(int data) {

if(!isempty()) {
data = stack[top];
top = top - 1;
return data;
} else {
printf("Could not retrieve data, Stack is empty.\n");
}
}

Array Representation of Stack:

1. To implement a stack items are inserted and removed at the same end
called Top
2. Insertion and deletion in the middle of the array or the linked list is not
allowed.
3. In the both cases insertion and deletion of elements is allowed one end
only
4. Suppose elements of the stack are integer type and stack store maximum
10 elements
#define MAX 10
Typedef struct
{
Int top;
Int elements[MAX];
} stack;
stack s;

24
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC

 Here we can define our own data type named stack


 Array elements hold the elements of stack
 Last line declares variables of type of stack

Fig : Stack array representation

Linked list representation of stack:


The major problem with the stack implemented using array is, it
works only for fixed number of data values. That means the amount of
data must be specified at the beginning of the implementation itself.
A stack data structure can be implemented by using linked list data
structure. The stack implemented using linked list can work for unlimited
number of values. That means, stack implemented using linked list works
for variable size of data. So, there is no need to fix the size at the
beginning of the implementation. The Stack implemented using linked
list can organize as many data values as we want.

Applications of Stack:
25
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC

1. Expression Evolution

2. Expression conversion

1. Infix to Postfix

2. Infix to Prefix

3. Postfix to Infix

4. Prefix to Infix

3. Parsing

4. Simulation of recursion

5. Fuction call

Expression Representation

Infix Prefix Postfix

a+b +ab ab+

a+b*c +a*bc abc*+

(a + b) * (c - d) *+ab-cd ab+cd-*

26
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC

Expression Evolution:

Evaluate an expression represented by a String. Expression can


contain parentheses; you can assume parentheses are well-matched. For simplicity,
you can assume only binary operations allowed are +, -, *, and /. Arithmetic
Expressions can be written in one of three forms:
Infix Notation: Operators are written between the operands they operate on,
e.g. 3 + 4 .
Prefix Notation: Operators are written before the operands, e.g + 3 4
Postfix Notation: Operators are written after operands.

Expression Example Note

Infix a+b Operator Between Operands

Prefix +ab Operator before Operands

Postfix ab+ Operator after Operands

Infix To Postfix:

1.(A+B^C)*D+E

=(A+BC ^)*D+E [ B^C Converted Into BC^ ]

2. (A+X)*D+E

=(AX +)*D+E [ A+X Converted Into AX+]

Infix Expression Prefix Expression Postfix Expression

A+B*C+D ++A*BCD ABC*+D+


Parsing:

(A + B) * (C + D) *+AB+CD AB+CD+*

27
A * B + C * D M.Tech.
G.NARESH, +*AB*CD AB*CD*+
DATASTRUCTURES

A+B+C+D +++ABCD AB+C+D+


PRAGATI WOMEN’S DEGREE COLLEGE II BSC

A parser is a software component that takes input data (frequently text) and builds
a data structure. Giving a structural representation of the input, checking for correct
syntax in the process.

The way to write arithmetic expression is known as


a notation. An arithmetic expression can be written in three different but equivalent
notations.

These notations are −

 Infix Notation

 Prefix (Polish) Notation

 Postfix (Reverse-Polish) Notation

Recursion:

Some computer programming languages allow a module or function to


call itself. This technique is known as recursion. In recursion, a function a either
calls itself directly.
Example − a function calling itself.

int function(int value) {


if(value < 1)
return;
function(value - 1);

printf("%d ",value);
}

28
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC

Example − a function that calls another function which in turn calls it again

int function(int value)


{
if(value < 1)
return;
function(value - 1);
printf("%d ",value);
}

Calling Function:

A called function performs a defined task and when its return statement is executed
or when its function-ending closing brace is reached.

To call a function, you simply


need to pass the required parameters along with the function name, and if the
function returns a value, then you can store the returned value.

Example:

int max(int num1, int num2);

int main () {

/* local variable definition */


int a = 100;
int b = 200;
int ret;

/* calling a function to get max value */


ret = max(a, b);

printf( "Max value is : %d\n", ret );

return 0;
}

29
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC

Queue:
Queue is an abstract data structure, somewhat similar to Stacks. Unlike
stacks, a queue is open at both its ends.
One end is always used to insert data(enqueue)
and the other is used to remove data(dequeue). Queue follows First-In-First-Out
methodology, i.e., the data item stored first will be accessed first.

Fig: Queue

A real-world example of queue can be a


single-lane one-way road, where the vehicle enters first, exits first. More real-
world examples can be seen as queues at the ticket windows and bus-stops.

Queue Representation:
As we now understand that in queue, we access both ends for
different reasons. The following diagram given below tries to explain queue
representation as data structure

As in stacks, a queue can also be implemented using Arrays, Linked-


lists, Pointers and Structures. For the sake of simplicity, we shall implement
queues using one-dimensional array.
30
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC

Basic Operations:

Here we shall try to understand the basic operations associated with queues −

 enqueue() − add (store) an item to the queue.

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

Few more functions are required to make the above-mentioned queue operation
efficient. These are −

 peek() − Gets the element at the front of the queue without removing it.

 isfull() − Checks if the queue is full.

 isempty() − Checks if the queue is empty.

In queue, we always dequeue (or access) data, pointed by front pointer and while
enqueing (or storing) data in the queue we take help of rear pointer.

Enqueue :

Algorithm:

Enqueue Operation:
Queues maintain two data pointers, front and rear. Therefore,
its operations are comparatively difficult to implement than that of stacks.

The following steps should be taken to enqueue (insert) data into a queue −

 Step 1 − Check if the queue is full.

 Step 2 − If the queue is full, produce overflow error and exit.

 Step 3 − If the queue is not full, increment rear pointer to point the next
empty space.

 Step 4 − Add data element to the queue location, where the rear is pointing.

31
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC

 Step 5 − return success.

 Sometimes, we also check to see if a queue is initialized or not, to handle


any unforeseen situations.

Algorithm for enqueue operation

procedure enqueue(data)
if queue is full
return overflow
endif
rear ← rear + 1
queue[rear] ← data
return true
end procedure

Implementation of enqueue() in C programming language −

Example

int enqueue(int data)


if(isfull())
return 0;
rear = rear + 1;
queue[rear] = data;
return 1;
end procedure

Dequeue Operation

32
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC

Accessing data from the queue is a process of two tasks −


access the data where front is pointing and remove the data after access. The
following steps are taken to perform dequeue operation –

 Step 1 − Check if the queue is empty.

 Step 2 − If the queue is empty, produce underflow error and exit.

 Step 3 − If the queue is not empty, access the data where front is pointing.

 Step 4 − Increment front pointer to point to the next available data element.

 Step 5 − Return success.

Algorithm for dequeue operation

procedure dequeue
if queue is empty
return underflow
end if
data = queue[front]
front ← front + 1
return true
end procedure

Implementation of dequeue() in programming language −

Example

int dequeue() {
if(isempty())
return 0;

33
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC

int data = queue[front];


front = front + 1;
return data;
}

Array Representation:

Array Implementation of a Queue. Conceptually, the


simplest way of implementing aqueue using an array is to make a policy decision
that element zero of the array is the head of the queue, and to always remove the
item from this location.

Fig : Array Representation

Linked Representation:

Elements of the queue are being stored in a linked list.


Recall that linked listsare made up of nodes that contain both an element and a
pointer to the next node.

Fig: Linked Representation

34
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC

Circular Queue:

Circular queue is a linear data structure. It follows FIFO


principle. In circular queue the last node is connected back to the first node to
make a circle. Circular linked list fallow the First In First Out principle. Elements
are added at the rear end and the elements are deleted at front end of the queue.

Fig: Circular queue

Algorithm for creating circular linked list:-


Step 1) start
Step 2) create anode with the following fields to store information and the address
Of the next node.
Structure node
Begin
int info
Pointer to structure node called next
end
Step 3) create a class called with the member variables of pointer to structure
nodes called root, prev, next and the member functions create ( ) to create
35
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC

the circular linked list and display ( ) to display the circular linked list.
Step 4) create an object
Step 5) create ( ) member function
Step 6) display ( ) member function
Step 7) stop

Circular Queue can be created in three ways they are


· Using single linked list
· Using double linked list
· Using arrays

Applications of circular queue:

Adding large integers:

Large integers can be added very easily using circular queues. Here the rightmost
digit is placed in the front node and leftmost digit is placed in the rear node.

Memory management:

The unused memory locations in the case of ordinary queues can be utilized
in circular queues.

Computer controlled traffic system:

In computer controlled traffic system, circular queues are used to switch on


the traffic lights one by one repeatedly as per the time set.

The common operations on circular queue are:

qstore(: adding elements at the end of a circular queue.

qdelete: removing elements from the front of the circular queue.

isfull: isfull finds out whether the circular queue is full

isempty: isempty finds out whether the circular queue is empty

create: to create an empty circular queue

Algorithm for Enqueue operation


36
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC

Step 1. start
Step 2. if (front == (rear+1)%max)
Print error “circular queue overflow “
Step 3. else
{
rear = (rear+1)%max
Q[rear] = element;
If (front == -1 ) f = 0;
}
Step 4. stop

Algorithm for Dequeue operation

Step 1. start
Step 2. if ((front == rear) && (rear == -1))
Print error “circular queue underflow “
Step 3. else
{
element = Q[front]
If (front == rear) front=rear = -1
Else
Front = (front + 1) % max
}
Step 4. Stop

Priority Queue:

A priority queue is different from a "normal" queue, because instead


of being a "first-in-first-out" data structure, values come out in order by priority.

In max priority queue, elements are inserted in the order in which


they arrive the queue and always maximum value is removed first from
the queue. ... The following are the operations performed in a Maxpriority queue.

37
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC

Consider a networking application where server has to respond for


requests from multiple clients using queue data structure. Assume 4 requests
arrived to the queue in the order of R1 requires 20 units of time,R2 requires 2 units
of time,R3 requires 10 units of time and R4 requires 5 units of time
Queue is as follows…

R1:2 R2:2 R3:1 R4:5


0 0

Front Rear
Now check waiting time for each request to be complete…

1. R1:20 units of time.


2. R2:22 units of time.(R2 must wait till R1 complete)
3. R3:32 units of time.(R3 must wait till R2 complete)
4. R4:37 units of time.(R4 must wait till R3 complete)

Basic Operations:

 insert / enqueue − add an item to the rear of the queue.

38
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC

 remove / dequeue − remove an item from the front of the queue.

 Peek − get the element at front of the queue.

 isFull − check if queue is full.

 isEmpty − check if queue is empty.

Implementing priority queues

Now let's consider how to implement priority queues using a heap. The standard
approach is to use an array (or an ArrayList), starting at position 1 (instead of 0),
where each item in the array corresponds to one node in the heap:

 The root of the heap is always in array[1].

 Its left child is in array[2].

 Its right child is in array[3].

Here's an example, showing both the conceptual heap (the binary tree), and its
array representation:

Fig: Implementation of Priority Queue

Types of Priority Queue:


There are two types of Priority Queues
1. Max-Priority queue
2. Min-Priority queue

1.Max-Priority queue:
39
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC

In max priority queue, elements are inserted in the order


in which they arrive the queue and always maximum value is removed first from
the queue.
For example assume that we insert in order 8,3,2,5 and they are removed in
the order 8,5,3,2
The operations performed in max priority queue:
1.isEmpty():-Check whether queue is empty
2.insert():-Insert a new value into the queue
3.findmax();-Find maximum value into the queue
4.delete():-Delete maximum value from the queue

2.Min-Priority queue:
Min Priority queue is similar to max priority queue expect
removing maximum elements first, we remove minimum element first in min
priority.
The operations performed in max priority queue:
1.isEmpty():-Check whether queue is empty
2.insert():-Insert a new value into the queue
3.findmin();-Find minimum value into the queue
4.remove():-Delete minimum value from the queue

2. Min Priority Queue Representations


Applications of Priority Queue:

1) CPU Scheduling
2) Graph algorithms like shortest path algorithm, Prim’s Minimum Spanning
Tree, etc
3) All queue applications where priority is involved.

40
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC

UNIT-3: TREES

Binary Tree:

Binary Tree is a special data structure used for data storage


purposes. A binary tree has a special condition that each node can have a
maximum of two children. A binary tree has the benefits of both an ordered array
and a linked list as search is as quick as in a sorted array and insertion or deletion
operation are as fast as in linked list.

Fig: Binary Tree

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

41
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC

1. Data
2. Pointer to left child
3. Pointer to right child

Properties:

1. The maximum number of nodes at level ‘l’ of a binary tree is 2l-1.


Here level is number of nodes on path from root to the node (including root
and node). Level of root is 1.
For root, l = 1, number of nodes = 21-1 = 1
Assume that maximum number of nodes on level l is 2l-1

2) Maximum number of nodes in a binary tree of height ‘h’ is 2h – 1.


Here height of a tree is maximum number of nodes on root to leaf path. Height
of a leaf node is considered as 1.

3) In a Binary Tree with N nodes, minimum possible height or minimum


number of levels is ⌈ Log2(N+1) ⌉

4) A Binary Tree with L leaves has at least ⌈ Log2L ⌉ + 1 levels


A Binary tree has maximum number of leaves when all levels are fully filled.

5) In Binary tree, number of leaf nodes is always one more than nodes with two
children.
L=T+1
Where L = Number of leaf nodes
T = Number of internal nodes with two children

There is a relationship between internal nodes and external nodes i.e. If


the number of internal nodes is N, the number of external nodes will be N+1.

The first property dealt with the relationship between internal and external
nodes. This property is dealing with the relationship of links to the internal nodes.
42
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC

Property:
1. In every rooted tree, each node, except the root, has a unique parent.
2. Every link connects a node to its parents,

3. Similarly each of the external nodes has one link to its parents.

Fig : Binary tree (Internal nodes, External nodes)

Types of Binary Tree:


Full Binary Tree A Binary Tree is full if every node has 0 or 2 children. Following are examples of full
binary tree.
18

/ \

15 30

/ \ / \

40 50 100 40

18

/ \

40 30
43
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC

/ \

100 40

In a Full Binary, number of leaf nodes is number of internal nodes plus 1


L=I+1
Where L = Number of leaf nodes, I = Number of internal nodes

Complete Binary Tree:


A Binary Tree is complete Binary Tree if all levels are
completely filled except possibly the last level and the last level has all keys as left
as possible
Following are examples of Complete Binary Trees
18
/ \
15 30
/ \ / \
40 50 100 40

Perfect Binary Tree A Binary tree is Perfect Binary Tree in which all internal
nodes have two children and all leaves are at same level.
Following are examples of Perfect Binary Trees.
18
/ \
15 30
/ \ / \
40 50 100 40

18
/ \
15 30

44
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC

A Perfect Binary Tree of height h (where height is number of nodes on path from
root to leaf) has 2h – 1 node.

BalancedBinaryTree:
A binary tree is balanced if height of the tree is O(Log n) where n is number of
nodes.

A degenerate (or pathological) tree


A Tree where every internal node has one child. Such trees are performance-
wise same as linked list.

10
/
20
\
30
\
40

Linked representation of Binary Tree:

We use double linked list to represent a binary tree. In a


double linked list every node consists of three fields. First field for storing left
child address, second for sorting actual data and third for storing right child
address. In this linked list representation, a node has the following structure…

Fig: Structure of Node

45
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC

1. The values of binary tree are stored in an array called as tree.

2. The root of the tree is stored at first location i.e. at tree[0](0 index).

Fig: Linking Representation of Binary Tree

46
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC

Fig: Storage Representation of Binary Tree

Binary Search Tree (BST):

A Binary Search Tree (BST) is a tree in which all the nodes follow the
below-mentioned properties −

 The left sub-tree of a node has a key less than or equal to its parent node's
key.

 The right sub-tree of a node has a key greater than to its parent node's key.

Thus, BST divides all its sub-trees into two segments; the left sub-tree and the
right sub-tree and can be defined as −

left_subtree (keys) ≤ node (key) ≤ right_subtree (keys)

47
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC

BST is a collection of nodes arranged in a way where they maintain BST


properties.

Fig: Binary Search Tree

We observe that the root node key (27) has all less-valued keys on the left sub-
tree and the higher valued keys on the right sub-tree.

Following are the basic operations of a tree −

 Search − Searches an element in a tree.

 Insert − Inserts an element in a tree.

 Pre-order Traversal − Traverses a tree in a pre-order manner.

 In-order Traversal − Traverses a tree in an in-order manner.

 Post-order Traversal − Traverses a tree in a post-order manner.

Node Representation:

Struct node
{
Int data;
Struct node *leftchild;
Struct node *rightchild;
};

Tree Traversals:

48
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC

There are three types of Tree traversals


1.In-Order
2.Pre-Order
3.Post-Order

Consider the Example:

Example Tree

DepthFirstTraversals:
(a)Inorder(Left,Root,Right) :42513
(b)Preorder(Root,Left,Right) :12453
(c) Postorder (Left, Right, Root) : 45231
Breadth First or Level Order Traversal : 1 2 3 4 5

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

Preorder Traversal:
Algorithm Preorder(tree)
49
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC

1. Visit the root.


2. Traverse the left subtree, i.e., call Preorder(left-subtree)
3. Traverse the right subtree, i.e., call Preorder(right-subtree)

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

Fig:In-Order,Pre-Order,Post-Order

Implementation of Binary search Tree:

Import java.util.Scanner;

Class BST node

Node left,right;

Int data;

Public BSTnode()

50
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC

left=null;

right=null;

data=0;

Public BSTnode(int n)

left=null;

right=null;

data=n;

Public void Setleft(BSTnode n)

left=n;

Public void Setright(BSTnode n)

right=n;

Public BSTnode Getleft()

Return left;

}
51
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC

Public BSTnode(int n)

Left=null;

Right=null;

Data=n;

Threaded Binary Trees:

Threaded Binary Tree is also a binary tree in which all left child pointers
that are NULL (in Linked list Representation) points to its in-order predecessor,
and all right child pointers that are Null (in Linked list representation) points to its
in-order successor.

Consider the following example….

To convert above binary tree into threaded binary tree, first find the in-order
traversal of that tree….

In-order traversal of binary tree…

H-D-I-B-E-A-F-J-C-G
When we represent above binary tree using linked list representation, nodes
H,I,E,F,J and G left child pointers are NULL. This NULL is replaced by address of
its in-order predecessor.

52
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC

Above example binary tree become as follows after converting into threaded
binary tree

In above figure threaded are indicated with dotted links.

Heap trees:

Heap is a special case of balanced binary tree data structure where the root-node
key is compared with its children and arranged accordingly. If α has child
node β then −

key(α) ≥ key(β)

53
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC

As the value of parent is greater than that of child, this property generates Max
Heap. Based on this criteria, a heap can be of two types –

1.Min-Heap

2.Max-Heap

For Input → 35 33 42 10 14 19 27 44 26 31
Min-Heap –

Where the value of the root node is less than or equal to either of its
children.

Fig:Min Heap

Max-Heap –

Where the value of the root node is greater than or equal to either of its children.

54
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC

Fig:Max-Heap

Both trees are constructed using the same input and order of arrival.

Max Heap Construction Algorithm


We shall use the same example to demonstrate how a Max Heap is created. The
procedure to create Min Heap is similar but we go for min values instead of max
values.

We are going to derive an algorithm for max heap by inserting one element at a
time. At any point of time, heap must maintain its property. While insertion, we
also assume that we are inserting a node in an already heapified tree.

Step 1 − Create a new node at the end of heap.


Step 2 − Assign new value to the node.
Step 3 − Compare the value of this child node with its parent.
Step 4 − If value of parent is less than child, then swap them.
Step 5 − Repeat step 3 & 4 until Heap property holds.
Max Heap Deletion Algorithm:

Step 1 − Remove root node.


Step 2 − Move the last element of last level to root.
Step 3 − Compare the value of this child node with its parent.
55
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC

Step 4 − If value of parent is less than child, then swap them.


Step 5 − Repeat step 3 & 4 until Heap property holds.

Min Heap deletion:

Removal operation uses the same idea as was used for insertion. Root's
value, which is minimal by the heap property.

1. Copy the last value in the array to the root;

2. Decrease heap's size by 1.

Example

Remove the minimum from a following heap:

Copy the last value in the array to the root and decrease heap's size by 1:

56
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC

Unit IV: GRAPHS

1. What is graph?Explain graph datastructure? Operations of graph?

Graph:

A graph is a pictorial representation of a set of objects where some pairs of


objects are connected by links. The interconnected objects are represented by
points termed as vertices, and the links that connect the vertices are called edges.

Formally, a graph is a pair of sets (V, E), where V is the set of vertices
and E is the set of edges, connecting the pairs of vertices. Take a look at the
following graph

57
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC

Fig: Graph

In the above graph,

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

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

Graph Data Structure


Mathematical graphs can be represented in data structure. We can represent a
graph using an array of vertices and a two-dimensional array of edges. Before we
proceed further, let's familiarize ourselves with some important terms −

 Vertex − Each node of the graph is represented as a vertex. In the following


example, the labeled circle represents vertices. Thus, A to G are vertices.
We can represent them using an array as shown in the following image.
Here A can be identified by index 0. B can be identified using index 1 and
so on.

 Edge − Edge represents a path between two vertices or a line between two
vertices. In the following example, the lines from A to B, B to C, and so on
represents edges. We can use a two-dimensional array to represent an array
as shown in the following image. Here AB can be represented as 1 at row 0,
column 1, BC as 1 at row 1, column 2 and so on, keeping other
combinations as 0.

58
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC

 Adjacency − Two node or vertices are adjacent if they are connected to


each other through an edge. In the following example, B is adjacent to A, C
is adjacent to B, and so on.

 Path − Path represents a sequence of edges between the two vertices. In the
following example, ABCD represents a path from A to D.

Fig : Graph

Basic Operations:
Following are basic primary operations of a Graph −

 Add Vertex − Adds a vertex to the graph.

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

59
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC

 Display Vertex − Displays a vertex of the graph.

Graph in Memory Representation:

Graph Representation:

There are Two types of graphs.

1.Un Directed graph

2.Directed graph

Un Directed Graph

Directed Graph

60
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC

ep Traversal Description

Initialize the stack.

1.

2. Mark S as visited and put


it onto the stack. Explore
any unvisited adjacent
node from S. We have
three nodes and we can
pick any of them. For this
example, we shall take
the node in an
alphabetical order.

61
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC

Mark A as visited and put


it onto the stack. Explore
any unvisited adjacent
node from A.
Both Sand D are adjacent
to A but we are
concerned for unvisited
nodes only.
3.

Visit D and mark it as


visited and put onto the
stack. Here, we
have B and C nodes,
which are adjacent
to D and both are
unvisited. However, we
shall again choose in an
4. alphabetical order.

62
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC

We choose B, mark it as
visited and put onto the
stack. Here Bdoes not
have any unvisited
adjacent node. So, we
pop Bfrom the stack.

5.

We check the stack top


for return to the previous
node and check if it has
any unvisited nodes.
Here, we find D to be on
the top of the stack.

7. Only unvisited adjacent


node is from D is C now.
So we visit C, mark it as
visited and put it onto

63
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC

2.Explain Components of graph?Types of graph?

Components of Graph:

A directed graph is called strongly connected if there is a path in each


direction between each pair of vertices of the graph. In a directed graph G that may
not itself be strongly connected, a pair of vertices u and v are said to be strongly
connected to each other if there is a path in each direction between them.

in the mathematical theory of directed graphs, a graph is said to


be strongly connected or diconnected if every vertex is reachable from every other
vertex. The strongly connected components or diconnected

Graph with strongly connected components marked

Un Directed graph:

A graph with only un directed edges is said to be undirected graph

Directed graph:
64
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC

A graph with only directed edges is said to be directed graph

Mixed graph:

A graph with directed and un directed edges is said to be mixed graph

Connected Components of a graph:

A connected component of a graph is a maximal subgraph in which the vertices are


all connected, and there are no connections between the subgraph and the rest of
the graph. A connected graph has only one connected component, which is the
graph itself, while unconnected graphs have more than one component. For
example, the graph shown below has three components, (0, 1, 2, 3), (4, 5, 6), and
(7, 8).

3.What is graph Traversal?Explain Graph Traversals(BFS,DFS)?

Graph Traversals:

Graph traversal is technique used for searching a vertex in a graph.


The graph traversal is also used to decide the order of vertices to be visit in the

65
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC

search process. Graph traversals find the edges to be used in the search process
without creating loops.

There are two graph traversals techniques and they are as follows…

1.DFS(Depth First Search)

2.BFS(Breath First Search)

1.DFS(Depth First Search):

Depth First Search (DFS) algorithm traverses a graph in a depthward


motion and uses a stack to remember to get the next vertex to start a search, when
a dead end occurs in any iteration.

Fig:Depth First Traversal

As in the example given above, DFS algorithm traverses from A to B to C to D


first then to E, then to F and lastly to G. It employs the following rules.

66
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC

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

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

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

2.BFS(Breath First Search):

BFS traversal of a graph. Produces a spanning tree as final result. Spanning tree
is a graph without any loops. We use queue data structure with maximum size of
total number of vertices in the graph to implement BFS traversal of a graph.

Fig: Breath First Search (BFS)

Breadth First Search (BFS) algorithm traverses a graph in a breadth ward


motion and uses a queue to remember to get the next vertex to start a search, when
a dead end occurs in any iteration.

67
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC

As in the example given above, BFS algorithm traverses from A to B to E to F


first then to C and G lastly to D. It employs the following rules.

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

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

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

4.Explain Basic searching Techniques(Binary Search, Linear Search)?

Basic Searching Techniques:

There are Two types of Searching Techniques

1. Binary Search

2. Linear Search

Binary Search:

Binary search is a fast search algorithm with run-time complexity of


Ο(log n). This search algorithm works on the principle of divide and conquer.

Binary search looks for a particular item by comparing the middle most item of the
collection. If a match occurs, then the index of item is returned. If the middle item
is greater than the item.

For a binary search to work, it is mandatory for the target array to be sorted. We
shall learn the process of binary search with a pictorial example. The following is
our sorted array and let us assume that we need to search the location of value 31
using binary search.

68
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC

First, we shall determine half of the array by using this formula −

mid = low + (high - low) / 2


Here it is, 0 + (9 - 0 ) / 2 = 4 (integer value of 4.5). So, 4 is the mid of the array.

Step 1 − Start searching data from middle of the list.


Step 2 − If it is a match, return the index of the item, and exit.
Step 3 − If it is not a match, probe position.
Step 4 − Divide the list using probing formula and find the new midle.
Step 5 − If data is greater than middle, search in higher sub-list.
Step 6 − If data is smaller than middle, search in lower sub-list.
Step 7 − Repeat until match.
Input Array: [1 2 3 4 6 7 9 11 12 14 15 16 17 19 33 34 43 45 55 66 ]
==================================================
Comparison 1
lowerBound : 0, intArray[0] = 1
upperBound : 19, intArray[19] = 66
Comparison 2
lowerBound : 10, intArray[10] = 15
upperBound : 19, intArray[19] = 66
Comparison 3
lowerBound : 15, intArray[15] = 34
upperBound : 19, intArray[19] = 66
Comparison 4
lowerBound : 18, intArray[18] = 55
upperBound : 19, intArray[19] = 66
Total comparisons made: 4
Element found at location: 19
Linear Search:

Linear search is a very simple search algorithm. In this type of search, a


sequential search is made over all items one by one. Every item is checked and if a
match is found then that particular item is returned, otherwise the search continues
till the end of the data collection.

Input Array: [1 2 3 4 6 7 9 11 12 14 15 16 17 19 33 34 43 45 55 66 ]
==================================================
69
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC

Total comparisons made: 19


Element found at location: 19

5.Explain Minimal Spanning Tree? Application of Spanning Tree,Properties of


Spanning tree:

Minimal Spanning Tree:

A spanning tree is a subset of Graph G, which has all the


vertices covered with minimum possible number of edges. Hence, a spanning tree
does not have cycles and it cannot be disconnected..

By this definition, we can draw a conclusion that every


connected and undirected Graph G has at least one spanning tree. A disconnected
graph does not have any spanning tree, as it cannot be spanned to all its vertices.

Fig : Minimal Spanning Tress

Application of Spanning Tree:

70
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC

Spanning tree is basically used to find a minimum path to connect all nodes in a
graph. Common application of spanning trees are −

1.Civil Network Planning

2.Computer Network Routing Protocol 3.Cluster Analysis

Properties of Spanning tree:


Following are a few properties of the spanning tree connected to graph G −

 A connected graph G can have more than one spanning tree.

 All possible spanning trees of graph G, have the same number of edges and
vertices.

 The spanning tree does not have any cycle (loops).

 Removing one edge from the spanning tree will make the graph
disconnected, i.e. the spanning tree is minimally connected.

 Adding one edge to the spanning tree will create a circuit or loop, i.e. the
spanning tree is maximally acyclic.

6.What is Minimum Spanning Tree?Explain Spanning tree algoritm(prim’s algorithm)


Minimum Spanning Tree (MST)
In a weighted graph, a minimum spanning tree is a spanning tree
that has minimum weight than all other spanning trees of the same graph. In real-
world situations, this weight can be measured as distance, congestion, traffic load
or any arbitrary value denoted to the edges.

71
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC

Fig: Example of Minimum Spanning Tree

Prim’s algorithm:
Prim's algorithm to find minimum cost spanning tree (as Kruskal's algorithm) uses
the greedy approach. Prim's algorithm shares a similarity with theshortest path
first algorithms.

Remove all loops and parallel edges in the given graph

72
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC

We can choose S node as the root node of Prim's spanning tree

we see that S,A and S,C are two edges with weight 7 and 8, respectively. We
choose the edge S,A as it is lesser than the other.

S-7-A-3-C tree is formed. Now


we'll again treat it as a node and
will check all the edges again.
However, we will choose only
the least cost edge. In this case,
C-3-D is the new edge, which is less than other edges' cost 8, 6, 4, etc.

73
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC

After this step, S-7-A-3-C tree is formed. Now we'll again treat it as a node and
will check all the edges again. C-3-D is the new edge, which is less than other
edges' cost 8, 6, 4, etc.

After adding node D to the spanning tree, we now have two edges going out of it
having the same cost, i.e. D-2-T and D-2-B. Thus, we can add either one. Hence,
we are showing a spanning tree with both edges included.

Kruskal’s Algorithm:
Kruskal's algorithm to find the minimum cost spanning tree uses the
greedy approach. This algorithm treats the graph as a forest and every node it has
as an individual tree. A tree connects to another.
To understand Kruskal's algorithm let us consider the following example −

74
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC

Step 1 - Remove all loops and Parallel Edges


Remove all loops and parallel edges from the given graph.

In case of parallel edges, keep the one which has the least cost associated and
remove all others.

Step 2 - Arrange all edges in their increasing order of weight


The next step is to create a set of edges and weight, and arrange them in an
ascending order of weightage (cost).

75
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC

Step 3 - Add the edge which has the least weightage


Now we start adding edges to the graph beginning from the one which has the
least weight. Throughout, we shall keep checking that the spanning properties
remain intact. In case, by adding one edge, the spanning tree property does not
hold then we shall consider not to include the edge in the graph.

The least cost is 2 and edges involved are B,D and D,T. We add them. Adding
them does not violate spanning tree properties, so we continue to our next edge
selection.
Next cost is 3, and associated edges are A,C and C,D. We add them again −

Next cost in the table is 4, and we observe that adding it will create a circuit in the
graph. −

76
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC

We ignore it. In the process we shall ignore/avoid all edges that create a circuit.

We observe that edges with cost 5 and 6 also create circuits. We ignore them and
move on.

Now we are left with only one node to be added. Between the two least cost edges
available 7 and 8, we shall add the edge with cost 7.

By adding edge S,A we have included all the nodes of the graph and we now have
minimum cost spanning tree.
Unit-V

Sorting & Searching

Selection Sort:

Selection sort is a simple sorting algorithm. This sorting algorithm is


an in-place comparison-based algorithm in which the list is divided into two parts,

77
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC

the sorted part at the left end and the unsorted part at the right end. Initially, the
sorted part is empty and the unsorted part is the entire list.

The smallest element is selected from the unsorted array and swapped with the
leftmost element, and that element becomes a part of the sorted array.

This algorithm is not suitable for large data sets as its average and worst case
complexities are of Ο(n2), where n is the number of items.

Step 1 − Set MIN to location 0


Step 2 − Search the minimum element in the list
Step 3 − Swap with value at location MIN
Step 4 − Increment MIN to point to next element
Step 5 − Repeat until list is sorted
How Selection Sort Works?
Consider the following depicted array as an example.

For the first position in the sorted list, the whole list is scanned sequentially.
The first position where 14 is stored presently, we search the whole list and find
that 10 is the lowest value.

So we replace 14 with 10. After one iteration 10, which happens to be the
minimum value in the list, appears in the first position of the sorted list.

For the second position, where 33 is residing, we start scanning the rest of the list
in a linear manner.

78
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC

We find that 14 is the second lowest value in the list and it should appear at the
second place. We swap these values.

After two iterations, two least values are positioned at the beginning in a sorted
manner.

The same process is applied to the rest of the items in the array.
Following is a pictorial depiction of the entire sorting process –

79
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC

Insertion Sort:

This is an in-place comparison-based sorting algorithm. Here, a sub-list is


maintained which is always sorted. For example, the lower part of an array is
maintained to be sorted. An element which is to be 'insert'ed in this sorted sub-list,
has to find its appropriate place and then it has to be inserted there. Hence the
name, insertion sort.

The array is searched sequentially and unsorted items are moved and
inserted into the sorted sub-list (in the same array). This algorithm is not suitable
for large data sets as its average and worst case complexity are of Ο(n 2), where n
is the number of items.

Algorithm:
Step 1 − If it is the first element, it is already sorted. return 1;
Step 2 − Pick next element
Step 3 − Compare with all elements in the sorted sub-list
Step 4 − Shift all the elements in the sorted sub-list that is greater than the
value to be sorted
Step 5 − Insert the value
Step 6 − Repeat until list is sorted

We take an unsorted array for our example.

Insertion sort compares the first two elements.

It finds that both 14 and 33 are already in ascending order. For now, 14 is in sorted
sub-list.

80
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC

Insertion sort moves ahead and compares 33 with 27.

And finds that 33 is not in the correct position.

It swaps 33 with 27. It also checks with all the elements of sorted sub-list. Here
we see that the sorted sub-list has only one element 14, and 27 is greater than 14.
Hence, the sorted sub-list remains sorted after swapping.

By now we have 14 and 27 in the sorted sub-list. Next, it compares 33 with 10.

These values are not in a sorted order.

So we swap them.

81
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC

However, swapping makes 27 and 10 unsorted.

Hence, we swap them too.

Again we find 14 and 10 in an unsorted order.

We swap them again. By the end of third iteration, we have a sorted sub-list of 4
items.

This process goes on until all the unsorted values are covered in a sorted sub-list.
Now we shall see some programming aspects of insertion sort.

Bubble Sort:

Bubble sort is a simple sorting algorithm. This sorting algorithm is


comparison-based algorithm in which each pair of adjacent elements is compared
and the elements are swapped if they are not in order. This algorithm is not
suitable for large data sets as its average and worst case complexity are of Ο(n 2)
where nis the number of items.

How Bubble Sort Works?


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

82
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC

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

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

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

The new array should look like this −

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

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

83
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC

We know then that 10 is smaller 35. Hence they are not sorted.

We swap these values. We find that we have reached the end of the array. After
one iteration, the array should look like this −

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

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

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

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

84
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC

Algorithm:
We assume list is an array of n elements. We further assume that swapfunction
swaps the values of the given array elements.

begin BubbleSort(list)

for all elements of list


if list[i] > list[i+1]
swap(list[i], list[i+1])
end if
end for

return list

end BubbleSort

Quick Sort:

Quick sort is a highly efficient sorting algorithm and is based on


partitioning of array of data into smaller arrays. A large array is partitioned into
two arrays one of which holds values smaller than the specified value, say pivot,
based on which the partition is made and another array holds values greater than
the pivot value.

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

Partition in Quick Sort


Following animated representation explains how to find the pivot value in an
array.

85
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC

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

Quick Sort Pivot Algorithm


Based on our understanding of partitioning in quick sort, we will now try to
write an algorithm for it, which is as follows.

Step 1 − Choose the highest index value has pivot


Step 2 − Take two variables to point left and right of the list excluding pivot
Step 3 − left points to the low index
Step 4 − right points to the high
Step 5 − while value at left is less than pivot move right
Step 6 − while value at right is greater than pivot move left
Step 7 − if both step 5 and step 6 does not match swap left and right
Step 8 − if left ≥ right, the point where they met is new pivot

Heap Sort:

86
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC

Heap sort is a comparison based sorting technique based on Binary Heap data
structure. It is similar to selection sort where we first find the maximum element
and place the maximum element at the end. We repeat the same process for
remaining element.

Heap is a special case of balanced binary tree data structure where the root-node
key is compared with its children and arranged accordingly. If α has child
node β then −

key(α) ≥ key(β)\

Initially on receiving an unsorted list, the first step in heap sort is to create
a Heap data structure(Max-Heap or Min-Heap). Once heap is built, the first
element of the Heap is either largest or smallest(depending upon Max-Heap or
Min-Heap), so we put the first element of the heap in our array.

As the value of parent is greater than that of child, this property generates Max
Heap. Based on this criteria, a heap can be of two types –

1.Max-Heap

2. Min-Heap

For Input → 35 33 42 10 14 19 27 44 26 31

Min-Heap –

Where the value of the root node is less than or equal to either of its
children.

87
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC

Fig: Min Heap

Max-Heap –

Where the value of the root node is greater than or equal to either of its
children.

Fig: Max Heap

Both trees are constructed using the same input and order of arrival.

Max Heap Construction Algorithm:

Step 1 − Create a new node at the end of heap.


Step 2 − Assign new value to the node.
Step 3 − Compare the value of this child node with its parent.
Step 4 − If value of parent is less than child, then swap them.
Step 5 − Repeat step 3 & 4 until Heap property holds.

88
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC

Max Heap Deletion Algorithm:

Step 1 − Remove root node.


Step 2 − Move the last element of last level to root.
Step 3 − Compare the value of this child node with its parent.
Step 4 − If value of parent is less than child, then swap them.
Step 5 − Repeat step 3 & 4 until Heap property holds.

Merge Sort:
Merge sort is a sorting technique based on divide and conquer technique.
With worst-case time complexity being Ο(n log n), it is one of the most respected
algorithms.
Merge sort first divides the array into equal halves and then combines them in a
sorted manner.
How Merge Sort Works?
To understand merge sort, we take an unsorted array as the following −

We know that merge sort first divides the whole array iteratively into equal halves
unless the atomic values are achieved. We see here that an array of 8 items is
divided into two arrays of size 4.

This does not change the sequence of appearance of items in the original. Now we
divide these two arrays into halves.

We further divide these arrays and we achieve atomic value which can no more be
divided.

89
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC

Now, we combine them in exactly the same manner as they were broken down.
Please note the color codes given to these lists.
We first compare the element for each list and then combine them into another list
in a sorted manner. We see that 14 and 33 are in sorted positions. We compare 27
and 10 and in the target list of 2 values we put 10 first, followed by 27. We change
the order of 19 and 35 whereas 42 and 44 are placed sequentially.

In the next iteration of the combining phase, we compare lists of two data values,
and merge them into a list of found data values placing all in a sorted order.

After the final merging, the list should look like this –

Now we should learn some programming aspects of merge sorting.


Algorithm:
Merge sort keeps on dividing the list into equal halves until it can no
more be divided. By definition, if it is only one element in the list, it is sorted.
Then, merge sort combines the smaller sorted lists keeping the new list sorted too.
Step 1 − if it is only one element in the list it is already sorted, return.
Step 2 − divide the list recursively into two halves until it can no more be divided.
Step 3 − merge the smaller lists into new list in sorted order.

90
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC

Binary search tree Deletion:

Remove operation on binary search tree is more complicated, than add and
search. Basically, in can be divided into two stages:

 search for a node to remove;

 if the node is found, run remove algorithm.

Remove algorithm in detail

Now, let's see more detailed description of a remove algorithm. First stage is
identical to algorithm for lookup , except we should track the parent of the
current node. Second part is more tricky. There are three cases, which are
described below.

1. Node to be removed has no children.

This case is quite simple. Algorithm sets corresponding link of the parent
to NULL and disposes the node.

Example. Remove -4 from a BST.

91
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC

2. Node to be removed has one child.

It this case, node is cut from the tree and algorithm links single child (with
it's subtree) directly to the parent of the removed node.

Example. Remove 18 from a BST.

92
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC

3. Node to be removed has two children.

This is the most complex case. To solve it, let us see one useful BST
property first. We are going to use the idea, that the same set of values may
be represented as different binary-search trees. For example those BSTs:

contains the same values {5, 19, 21, 25}. To transform first tree into
second one, we can do following:

93
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC

o choose minimum element from the right subtree (19 in the example);

o replace 5 by 19;

o hang 5 as a left child.

The same approach can be utilized to remove a node, which has two
children:

o find a minimum value in the right subtree;

o replace value of the node to be removed with found minimum. Now,


right subtree contains a duplicate!

o apply remove to the right subtree to remove a duplicate.

Notice, that the node with minimum value has no left child and, therefore,
it's removal may result in first or second cases only.

Example. Remove 12 from a BST.

Find minimum element in the right subtree of the node to be removed. In


current example it is 19.

94
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC

Replace 12 with 19. Notice, that only values are replaced, not nodes. Now
we have two nodes with the same value.

Remove 19 from the left subtree.

95
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC

Arrays Advantages:

1. It is used to represent multiple data items of same type by using only single
name.

2. It can be used to implement other data structures like linked lists, stacks, queues,
trees, graphs etc.

3. 2D arrays are used to represent matrices.

Arrays Disadvantages:

1. We must know in advance that how many elements are to be stored in array.

2. Array is static structure. It means that array is of fixed size. The memory which
is allocated to array can not be increased or reduced.

3. Since array is of fixed size, if we allocate more memory than requirement then
the memory space will be wasted. And if we allocate less memory than
requirement, then it will create problem.

4. The elements of array are stored in consecutive memory locations. So insertions


and deletions are very difficult and time consuming.

96
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC

Advantages and Disadvantages of Linked List

Advantages of Linked List

Dynamic Data Structure


Linked list is a dynamic data structure so it can grow and shrink at runtime by
allocating and deallocating memeory. So there is no need to give initial size of
linked list.

Insertion and Deletion


Insertion and deletion of nodes are really easier. Unlike array here we don’t have to
shift elements after insertion or deletion of an element. In linked list we just have
to update the address present in next pointer of a node.

No Memory Wastage
As size of linked list can increase or decrease at run time so there is no memory
wastage. In case of array there is lot of memory wastage, like if we declare an
array of size 10 and store only 6 elements in it then space of 4 elements are wasted.
There is no such problem in linked list as memory is allocated only when required.

Implementation
Data structures such as stack and queues can be easily implemented using linked
list.

Disadvantages of Linked List:

Memory Usage
More memory is required to store elements in linked list as compared to array.
Because in linked list each node contains a pointer and it requires extra memory
for itself.

Traversal

97
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC

Elements or nodes traversal is difficult in linked list. We cannot randomly access


any element as we do in array by index. For example if we want to access a node at
position n then we have to traverse all the nodes before it. So, time required to
access a node is large.

Reverse Traversing
In linked list reverse traversing is really difficult. In case of doubly linked list its
easier but extra memory is required for back pointer hence wastage of memory.
If you know some other advantages and disadvantages of linked list then please
mention by commenting below.

Applications of Binary Search Tree:

1. Binary search trees are collections that can efficiently maintain a


dynamically changing dataset in sorted order
2. Binary trees are a good way to express arithmetic expressions
3. The binary search tree is a different way of structuring data so that it can still
be binary searched
4. Binary search trees support everything you can get from a sorted array:
efficient search, in-order forward/backwards traversal from any given
element.
5. It may also be used to solve some of database problems, for example,
indexing.
6. Binary Search Tree - Used in many search applications where data is
constantly entering/leaving.

7. It is used to implement dictionary.


8. It is used to implement multilevel indexing in DATABASE.
9. Binary Search Tree - Used in many search applications where data is
constantly entering/leaving, such as the map and set objects in many
languages' libraries.
10.Binary Space Partition - Used in almost every 3D video game to
determine what objects need to be rendered.
11.Binary Tries - Used in almost every high-bandwidth router for storing
router-tables.

Goals Of Data Structures:


98
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC

1. A data structure is a specialized format for organizing and storing data.


General data structure types include the array, the file, the record, the
table, the tree, and so on.
2. Anydata structure is designed to organize data to suit a specific purpose
so that it can be accessed and worked with in appropriate ways.
3. Goal of data structure is simple to make data handling logic easy and
reusable.
4. The goals of the data structure is to retrieve data efficiently from
computer.
5. In computer programming, a data structure may be selected or designed
to store data for the purpose of working on it with various algorithms.
6. The goal of ds is done by describing, for each data structure, the amount
of space and time required for typical operations.

Deque :
A double-ended queue is a special type of data in the field of computer
programming. In this abstract data type, elements can be added from both the front
and the back of the queue. Double Ended Queue is also a Queue data structure in
which the insertion and deletion operations are performed at both the ends
(front and rear). That means, we can insert at both front and rear positions and can
delete from both front and rear positions.

Double Ended Queue can be represented in TWO ways, those are as follows...

1. Input Restricted Double Ended Queue

2. Output Restricted Double Ended Queue

99
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC

Input Restricted Double Ended Queue:

In input restricted double ended queue, the insertion operation is performed at only
one end and deletion operation is performed at both the end

Output Restricted Double Ended Queue


In output restricted double ended queue, the deletion operation is performed at only
one end and insertion operation is performed at both the ends.

Operations on Deque:
Mainly the following four basic operations are performed on queue:
insertFront(): Adds an item at the front of Deque.
insertLast(): Adds an item at the rear of Deque.
deleteFront(): Deletes an item from front of Deque.
deleteLast(): Deletes an item from rear of Deque.

In addition to above operations, following operations are also supported


getFront(): Gets the front item from queue.
getRear(): Gets the last item from queue.
isEmpty(): Checks whether Deque is empty or not.
isFull(): Checks whether Deque is full or not.

100
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC

Applications of Deque:
1.Since Deque supports both stack and queue operations, it can be used as both.

2. The Deque data structure supports clockwise and anticlockwise rotations in O(1)
time which can be useful in certain applications.

3. Also, the problems where elements need to be removed and or added both ends
can be efficiently solved using Deque.

101
G.NARESH, M.Tech.
DATASTRUCTURES

You might also like