Data Structures
Data Structures
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 −
Integers
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.
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.
Fig:Data Structure
2
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC
Processor speed − Processor speed although being very high, falls limited
if the data grows to billion records.
(or)
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.
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.
Non linear data structures are in which all the data are arranged in
random manner.
Linear List:
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.
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.
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.
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.
Linked Representation:
A linked-list is a sequence of data structures which are
connected together via links.
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.
7
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC
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:
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:
Tree
Graph:
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
V = {a, b, c, d, e}
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.
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.
Insertion Operation:
Insertion is a three step process
11
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC
Deletion Operation:
Deletion is a two step process
12
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC
Advanced Operations:
Following are the advanced operations specified for a 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
Fig: Insertion
Fig: Insertion
Deletion:
In the Single Linked List insertion operation can be performed by three ways
14
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC
Advantages:
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.
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.
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
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.
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
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:
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 −
20
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC
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.
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 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.
If the linked list is used to implement the stack, then in step 3, we need to allocate
space dynamically.
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:
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
Step 3 − If the stack is not empty, accesses the data element at whichtop is
pointing.
if stack is empty
return null
endif
data ← stack[top]
top ← top - 1
return data
end procedure
Example
if(!isempty()) {
data = stack[top];
top = top - 1;
return data;
} else {
printf("Could not retrieve data, Stack is empty.\n");
}
}
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
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
(a + b) * (c - d) *+ab-cd ab+cd-*
26
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC
Expression Evolution:
Infix To Postfix:
1.(A+B^C)*D+E
2. (A+X)*D+E
(A + B) * (C + D) *+AB+CD AB+CD+*
27
A * B + C * D M.Tech.
G.NARESH, +*AB*CD AB*CD*+
DATASTRUCTURES
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.
Infix Notation
Recursion:
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
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.
Example:
int main () {
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
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
Basic Operations:
Here we shall try to understand the basic operations associated with queues −
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.
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 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
procedure enqueue(data)
if queue is full
return overflow
endif
rear ← rear + 1
queue[rear] ← data
return true
end procedure
Example
Dequeue Operation
32
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC
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.
procedure dequeue
if queue is empty
return underflow
end if
data = queue[front]
front ← front + 1
return true
end procedure
Example
int dequeue() {
if(isempty())
return 0;
33
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC
Array Representation:
Linked Representation:
34
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC
Circular Queue:
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
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.
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
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:
37
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC
Front Rear
Now check waiting time for each request to be complete…
Basic Operations:
38
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC
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:
Here's an example, showing both the conceptual heap (the binary tree), and its
array representation:
1.Max-Priority queue:
39
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC
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
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:
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:
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
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.
/ \
15 30
/ \ / \
40 50 100 40
18
/ \
40 30
43
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC
/ \
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.
10
/
20
\
30
\
40
45
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC
2. The root of the tree is stored at first location i.e. at tree[0](0 index).
46
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC
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 −
47
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC
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.
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
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
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
Import java.util.Scanner;
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;
left=n;
right=n;
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 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.
To convert above binary tree into threaded binary tree, first find the in-order
traversal of that 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
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.
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.
Removal operation uses the same idea as was used for insertion. Root's
value, which is minimal by the heap property.
Example
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
Graph:
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
V = {a, b, c, d, e}
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
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 Edge − Adds an edge between the two vertices of the graph.
59
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC
Graph Representation:
2.Directed graph
Un Directed Graph
Directed Graph
60
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC
ep Traversal Description
1.
61
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC
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.
63
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC
Components of Graph:
Un Directed graph:
Directed graph:
64
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC
Mixed graph:
Graph Traversals:
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…
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.)
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.
67
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.
Insert it in a queue.
Rule 2 − If no adjacent vertex is found, remove the first vertex from the
queue.
1. Binary Search
2. Linear Search
Binary Search:
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
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
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 −
All possible spanning trees of graph G, have the same number of edges and
vertices.
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.
71
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC
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.
72
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC
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.
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
In case of parallel edges, keep the one which has the least cost associated and
remove all others.
75
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC
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
Selection Sort:
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.
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:
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
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
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.
So we swap them.
81
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC
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:
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.
Next we compare 33 and 35. We find that both are in already sorted positions.
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.
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)
return list
end BubbleSort
Quick Sort:
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.
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.
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
Max-Heap –
Where the value of the root node is greater than or equal to either of its
children.
Both trees are constructed using the same input and order of arrival.
88
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC
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 –
90
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC
Remove operation on binary search tree is more complicated, than add and
search. Basically, in can be divided into two stages:
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.
This case is quite simple. Algorithm sets corresponding link of the parent
to NULL and disposes the node.
91
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC
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.
92
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC
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;
The same approach can be utilized to remove a node, which has two
children:
Notice, that the node with minimum value has no left child and, therefore,
it's removal may result in first or second cases only.
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.
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.
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.
96
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC
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.
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
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.
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...
99
G.NARESH, M.Tech.
DATASTRUCTURES
PRAGATI WOMEN’S DEGREE COLLEGE II BSC
In input restricted double ended queue, the insertion operation is performed at only
one end and deletion operation is performed at both the end
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.
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