DS - Notes - Unit 1 2 4 5
DS - Notes - Unit 1 2 4 5
STUDENT ADVISORY
Dear Students,
Please be informed that the notes provided by the institute
offer a concise presentation of the syllabus. While these notes
are helpful for an overview and quick revision, We would
strongly suggest that you refer to the prescribed textbooks /
Reference book for a comprehensive understanding and
thorough preparation of all exams and writing in the
examination.
Best regards,
LJ Polytechnic.
પ્રિય પ્રિદ્યાર્થીઓ,
એલજે પોક્ષલટેકપ્રનક.
Data Structures Introduction to Data Structures Unit-1
Introduction
A data structure defines a way of organizing all data items that considers not only the elements
stored but also their relationship to each other. The term data structure is used to describe the
way data is stored.
Arrays
1) Storing list of data elements belonging to same data type.
2) Auxiliary storage for other data structures.
3) Storage of binary tree elements of fixed count.
4) Storage of matrices.
Linked List
1) Implementing stacks, queues, binary trees and graphs of predefined size.
2) Implement dynamic memory management functions of operating system.
3) Polynomial implementation for mathematical operations
4) Circular linked list is used to implement OS or application functions that require round
robin execution of tasks.
5) Doubly linked list is used in the implementation of forward and backward buttons in a
browser to move backwards and forward in the opened pages of a website.
6) Circular queue is used to maintain the playing sequence of multiple players in a game.
Stack
1) Temporary storage structure for recursive operations.
2) Evaluation of arithmetic expressions in various programming languages.
3) Conversion of infix expressions into postfix expressions.
4) Checking syntax of expressions in a programming environment.
String
1) In all the problems solutions based on backtracking.
2) Used in depth first search in graph and tree traversal.
3) UNDO and REDO functions in an editor.
Data Structures Introduction to Data Structures Unit-1
Queues
1) It is used in breadth search operation in graphs.
2) Job scheduler operations of OS like a print buffer queue, keyboard buffer queue to store
the keys pressed by users.
3) Job scheduling, CPU scheduling, Disk Scheduling.
4) Priority queues are used in file downloading operations in a browser.
Trees
1) Implementing the hierarchical structures in computer systems like directory and file
system.
2) Implementing the navigation structure of a website.
3) Decision making in gaming applications.
4) Implementation of priority queues for priority-based OS scheduling functions.
5) Parsing of expressions and statements in programming language compilers.
Properties of an Algorithm
Key Features
Input - An algorithm should have 0 or more finite number of well-defined inputs.
Output - An algorithm should have 1 or more well-defined outputs, and should match
the desired output.
Definiteness - Algorithm should be clear and unambiguous. Each of its steps (or phases), and
their inputs and outputs should be clear and must lead to only one meaning.
Finiteness - Algorithms must terminate after a finite number of steps.
Effectiveness – Every step of an algorithm must be effective or have some meaning.
Feasibility - An algorithm must be feasible. It means it should be possible to implement.
Correctness - For every input an algorithm should produce correct output.
Example of an algorithm
Write an algorithm to find average of two number.
Space Complexity
It is the total memory space required by the program for its execution.
Declaration of an array: We know that all the variables are declared before they are used in the
program. During declaration, the size of the array has to be specified. The size used during
declaration of the array informs the compiler to allocate and reserve the specified memory
locations.
Initialization of Arrays: We can initialize the elements of arrays in the same way as the
ordinary variables when they are declared. The two different types of initializing arrays are:
1. At Compile time
2. At Run Time
Arrays can be initialized at the time of declaration when their initial values are known in
advance. Array elements can be initialized with data items of type int, char etc.
The above statements will initialize array elements with the values entered through the key
board. We can also use for loop like,
Data Structures Introduction to Data Structures Unit-1
for(i=0;i<3;i++)
scanf(“%d”,&x[i]);
printf(“%d %d %d”,x[0],x[1],x[2]);
OR
Declaration
Syntax: data_type array_name[row_size][column_size];
Example: int arr[3][3];
Where first index value shows the number of the rows and second index value shows the
number of the columns in the array.
Initializing two-dimensional arrays:
We can also initialize a two-dimensional array in the form of a matrix as shown below
int a[2][3]={
{0,0,0},
{1,1,1}
};
When the array is completely initialized with all values, explicitly we need not specify the size
of the first dimension.
If the values are missing in an initializer, they are automatically set to zero.
Data Structures Introduction to Data Structures Unit-1
An array can be explicitly initialized at run time. This approach is usually applied for
initializing large arrays. scanf can be used to initialize an array.
Example:
int x[2][3];
scanf(“%d %d %d %d %d %d”,&x[0][0],&x[0][1],&x[0][2] ,&x[1][0],&x[1][1],&x[1][2]);
The above statements will initialize array elements with the values entered through the key
board.
OR
We can also use for loop like,
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
{
scanf(“%d”, &x[i][j]);
}
}
Display elements of array:
OR
Declaring Strings
C does not support string as a data type. It allows us to represent strings as character arrays.
In C, a string variable is any valid C variable name and is always declared as an array of
characters.
Data Structures Introduction to Data Structures Unit-1
Initializing strings
There are several methods to initialize values for string variables.
Example: char city[] = ”NEWYORK”;
char city[8] ={‘N’,’E’,’W,’Y’,’O’,’R’,’K,’\0’};
The string city size is 8 but it contains 7 characters and one character space is for NULL
terminator.
getchar()
This library function is used to get single character from the terminal.
char ch;
ch = getchar();
gets()
This library function read line of text containing white space until new line character.
char str[5];
gets(str);
printf()
The standard printf function is used for printing or displaying a string on an output device.
The format specifier used is %s.
printf("%s", name);
puts()
The puts function prints the string on an output device and moves the cursor back to the first
position.
char str[5]=”data”;
puts(str);
putchar()
The C library function putchar() is used to print a single character on the terminal.
char str[5]=”data”;
int i;
for(i=0;i<10;i++)
putchar(str[i]);
Data Structures Introduction to Data Structures Unit-1
Stack
Stack is a linear list in which insertion and deletion operations are performed at only one end of
the list. A stack is generally implemented with only two operations: PUSH and POP. The
insertion operation is referred to as a PUSH operation. The deletion operation is referred to as a
POP operation.
A pointer TOP keeps track of the top element in stack. Initially when the stack is empty, TOP
has a value of zero and when the stack contains a single element: TOP has a value of one and so
on. Each time a new element is inserted in the stack the TOP pointer is incremented by one and
the pointer is decremented by one when element is deleted. Example – pile of tray in cafeteria.
PUSH Operation
To insert an element on the TOP of the stack is called PUSH operation.
PUSH(S, TOP, X)
This algorithm inserts an element on top of the stack.
S represents stack.
TOP is a pointer which points to the top of the stack.
Step 1: [check for stack overflow]
if (TOP>=N)
then write (“Stack is Overflow”)
return ()
Step 2: [Increment TOP]
TOP ← TOP +1
Step 3: [Insert element]
S[TOP] ← X
Step 4: [finished]
return ()
Data Structures Stack and Queue Unit-2
POP Operation
To remove an element from the TOP of the stack is called POP operation.
Applications of Stack
Three main applications of stack are: (1) Recursion (2) Stack machines (3) Polish notation. The
recursive function is called function call to itself. Stack machine provides faster execution of
polish notation. Better used for stacking local machines. It is used for representation of
arithmetic expression. The process of writing the operators of an expression either before those
operands or after operands are called the Polish Notation. There are basically three types of
polish notation: Infix, Prefix, Postfix
Recursion
Recursion is a problem solving approach in which a problem is solved using repeatedly
applying the same solution to smaller instances. Recursive function is a programming technique
that allows the programmer to express operations in terms of themselves. The recursive
function is called function call to itself.
Stack machines
Stack machine provides faster execution of polish notation. Better used for stacking local
machines.
Polish notation
It is used for representation of arithmetic expression. The process of writing the operators of an
expression either before those operands or after operands are called the Polish Notation. There
are basically three types of polish notation: Infix, Prefix, Postfix
Data Structures Stack and Queue Unit-2
Recursive Functions
Recursion is a problem-solving approach in which a problem is solved using repeatedly
applying the same solution to smaller instances. Recursive function is a programming technique
that allows the programmer to express operations in terms of themselves. The recursive
function is called function call to itself.
Factorial of Number
The factorial function can be recursively defined as,
Factorial(n) = 1 if n = 0
= n * factorial(n-1) if n > 0
Fibonacci series
The function of Fibonacci series can be recursively defined as,
Take n as input
if n=0 or n=1 then, fibo(n) = 0
else if n=2 then, fibo(n) = 1
else fibo(n) = fibo(n-1) + fibo(n-2)
Q.5 Explain steps to convert infix expression to postfix expression using stack.
1) Print operands as they arrive.
2) If stack is empty or contains a left parenthesis on TOP, push the incoming operator onto
the stack.
3) If incoming symbol is ‘(‘, push it onto stack.
4) If incoming symbol is ‘)’, pop the stack and print operators until left parenthesis is found.
5) If incoming symbol has higher precedence then the TOP of the stack.
6) If incoming symbol has lower precedence then the TOP of the stack, pop and print the
TOP. Then test the incoming operator against the new TOP of the stack.
7) If incoming operator has equal precedence with the TOP of the stack, use associativity
rule.
8) If expression ends then pop and print all operators of stack.
Data Structures Stack and Queue Unit-2
Queue
A queue is a linear list of elements in which deletion can take place only at one end, called the
FRONT, and insertions can take place only at the other end, called the REAR. Queue is also
called First-in-First-out (FIFO) lists.
The term “front” and “rear” are used in describing a linear list only when it is implemented as
a queue. Since the first element in a queue will be the first element out of the queue. In other
words, the order in which elements enters a queue is the order in which they leave.
Real life examples of Queue are a row of students at a registration center, a movie ticket
window example, line of cars waiting to proceed at traffic signal etc.
Deletion in Queue
To remove an element at the FRONT end is called DELETION operation.
Q_DELETE (Q, F, R, N)
Q represents queue vector containing N elements.
F and R are pointers pointing to the FRONT and REAR end.
Step 1: [Check for Queue underflow]
if F = 0
then write(“Queue is underflow”)
return (0)
Step 2: [Delete element]
Y ← Q[F]
Step 3: [Check for Queue empty]
If F = R
then F ← 0
R←0
Else
F←F+1
Step 4: [return element]
return(Y)
CQ_INSERT (Q, F, R, N, Y)
This operation inserts an element in the circular queue.
Q represents Queue vector containing N elements.
F and R are pointers pointing to the FRONT and REAR end.
Y is the element to be inserted.
Initially F and R are set to 0.
Step 1: [Reset rear pointer]
if R >= N
then R ← 1
Else R ← R + 1
Step 2: [Overflow?]
if F = R
then write(“QUEUE OVERFLOW”)
Data Structures Stack and Queue Unit-2
return ()
Step 3: [Insert element]
Q[R] ← Y
Step 4: [Is front pointer properly set?]
if F=0
then F ← 1
return ()
Applications of Queue
A queue is the natural data structure for a system to serve its incoming requests. Most of the
process scheduling algorithm in operating system uses queues. Queues are used to schedule
various jobs, tasks and processes for their execution by the CPU. Simulation is an application
of Queue which allows experimenting without modifying the original situation.
Data Structures Stack and Queue Unit-2
Q.12 State the limitations of a Simple Queue and explain Circular Queue data
structure.
1) The limitation of simple Queue is that even if we have free spaces, we cannot use these
memory spaces. So, simple queue results in wastage of memory. This problem can be
solved by using Circular Queue.
2) A Circular queue is a queue in which data are arranged such that the first element in the
queue follows the last element in the queue.
3) When we are deleting an element from simple queue, front pointer is incremented by one
and the previous place of front pointer becomes useless.
4) If rear pointer reaches to last element, we cannot insert any more elements. So wasting of
memory is there, this problem solved by Circular queue.
5) As by moving ahead, when front pointer or rear pointer reaches at last in the next move it
moves to the first position.
Data Structure
Binary Tree
Tree
Definition
Data structures where data elements are not arranged sequentially or linearly are called
non-linear data structures. Tree is an example of non-linear data structure.
The Data Structure which is used to represent the hierarchical relationship between data
element, with a special node named root and each node of data structure Stores a data
value and has zero or more pointer to pointing to the other nodes which named ad child
nodes, that data structure is called tree.
For example: Family trees, table of Contents, Directories Stored in Computer, Decimal
Classification of books in library and records.
Trees are very useful in describing any Structure which involves hierarchy.
Terminology
Binary tree: The Binary tree is a special type of tree, which can be either empty or has finite
set of nodes such that, one of the nodes is designated as root node and the remaining nodes are
partitioned into two sub trees of root node known as left sub tree and right sub tree.
It is a tree in which each node can have maximum two children or you can say at most two
children.it means each node can have 0,1 or 2 children but cannot have more than two children.
Out degree: In a directed graph, for any node v the number of edges which have v as their
initial node is called the outdegree of node v.
Degree: In a tree the sum of edges Comes into particular node and edge Comes Out from
Particular node is called degree of that Node.
Leaf Node: The nodes in the tree which have no child node or which are at the lowest level
of the tree are called as leaf node.
Directed Edge: In a tree an edge which is given direction from onr Node to another Node
then it is called Directed edges.
Complete binary tree: A complete binary tree is a binary tree in which every level, except
possibly the last, is completely filled, and all nodes are as far left as possible.
Root node: The node in the tree which is designated at the top of the tree and it has no parent
node is called as Root Node.
Strictly binary tree: If every non-leaf node in a binary tree has nonempty left and right sub-
trees, the tree is called a strictly binary tree.
Depth: The depth of a node is the number of edges from the node to the tree's root node. A
root node will have a depth of 0. The height of a node is the number of edges on the longest
path from the node to a leaf.
General Tree: General tree is a tree in which each node can have either zero or many child
nodes.
Siblings: The Nodes which belonging to the same parent Node are known as Siblings Node.
Step 1:
Data Structure
Step 2:
Because of the above-mentioned characteristics binary search tree allow faster insertion
deletion and searching facility
Operations on Binary search Tree
Insertion
Insertion of a Node in Binary search Tree:
1. All the nodes in a left sub tree having values less then root node.
2. All the Nodes in a right sub tree having values greater than root node.
Deletion
In order to delete node from binary search tree we have to consider three possibilities.
1. A node to be deleted has no sub tree
2. A node to be deleted has only one sub tree (left or right).
3. A node to be deleted has two sub trees (left and right)
Possibility 1:
It is the simplest case, in this case, replace the leaf node with the NULL and simple free the
allocated space. In the following image, we are deleting the node 18, since the node is a leaf
node, therefore the node will be replaced with NULL and allocated space will be freed.
Possibility 2:
In this case, replace the node with its child and delete the child node, which now contains the
value which is to be deleted. Simply replace it with the NULL and free the allocated space.
In the following image, the node 25 is to be deleted. It has only one child. The node will be
replaced with its child node and the replaced node 25 (which is now leaf node) will simply be
deleted.
Possibility 3:
If a node to be deleted has two sub trees left as well as right.in such case we have to perform
following steps
1. Find in order child of the node to be deleted.
2. Append the right sub-tree of the in-order child to its grant parent.
3. Replace the node to be deleted with its in-order child.
Searching
In order to searching a node in binary search tree we have to follows the step given below.
Step-1
First, we have to check weather binary search tree is empty or not. If binary search tree is
empty then search is un successful.
Step-2
If binary search tree is not empty then we compare the value of a node to be searched with
root node of binary tree if both values are equal then search is Successful otherwise, we have
two possibilities.
1. If the value of the node to be searched having value less than the value of root node then
we have to search the node in left subtree of root node.
2. If the value of the node to be searched having value greater than the value of root node
Data Structure
Step 2 is repeated recursively until node to be searched is found or all the nodes in binary
search tree are compared with the value of the node to be searched.
Tree Traversal
Traversal is the method of processing each and every node in the Binary Search Tree exactly
once in Systemic manner. There are three different type of tree traversal.
1. Preorder Traversal
2. Inorder Traversal
3. Postorder Traversal
Pre-order Traversal
In Order to traverser the free in preorder follow the steps given below
1. Process the root node first.
2. Traverse the left sub tree in preorder.
3. Traverse the right sub tree in preorder.
Algorithm for pre-order traversal
In-order Traversal
In order to traverse the tree in in-order follow the steps given below:
1. Traverse the left sub-tree in in-order.
2. Process the root node.
3. Traverse the right sub-tree in-order.
Post-order Traversal
In order to traverse the tree in post-order follow the steps given below.
1. Traverse the left sub tree in post-order.
2. Traverse the right sub tree in post-order.
3. Process the root node.
Sorting:
Definition
1. Internal Sort
The Sorting method that does not required external memory for sorting the
elements is known as internal sort. It is useful when we must sort fewer amounts
of elements.
Example:
1. Bubble Sort
2. Quick Sort
3. Selection Sort
4. Insertion Sort
2. External Sort
The sorting method that required external memory for sorting the element is
known as external Sort. It is useful when we must sort large number of elements.
Example:
1. Merge Sort
2. Radix Sort
Data Structure
Example:
Algorithm:
Step 1: Repeat up to Step 3 for I=0 to N-1
Step 2: Repeat step 3 for J=0 to N-I-1
Step 3: If a[J] > a[J+1] then
TEMP a[J]
a [ J] a[J+1]
a[J+1] TEMP
Step 4: Exit
Data Structure
Algorithm:
Step 1: Repeat up to Step 5 for i=0 to N-1
Step 2: Min a[i]
Pos i
Step 3: Repeat Step 4 for j=i+1 to N
Step 4: if a[j] < Min then
Min a[j]
Pos j
Step 5: TEMP a[i]
a[i] a[Pos]
a[Pos] TEMP
Step 6: Exit
Data Structure
A very simple example of insertion sort is when we are planning a game of cards,
we are taking cards one by one and arranging them accordingly.
Example:
Algorithm:
Step 1: [initialize i]
I 1
Step 2:[traverse through the list and compare elements]
Repeat while (i<n)
KEY a[i]
J i-1
Repeat while (j <= 0 and KEY < a[j])
a[j+1] a[j]
j j-1
a[j+1] KEY
I i+1
Step 3: [finish]
Return ()
Data Structure
Algorithm:
Mergesort(a,i,j)
Step 1:
i low
j high
Step 2:
Mid (i+j)/2
Mergesort(a,i,mid)
Mergesort(a,mid+1,j)
Step 3:
Merge(a, i, mid, j)
Algorithm: Merge(a, i, mid,j)
Step 1:
i low
j mid+1
k low
Step 2:
Repeat Step 3 for i<=mid and j<=high
Step 3:
If(a[i] <= a[j])
b[k] a[i]
Data Structure
i i++
else
b[k] a[j]
j j+1
Step 4: k k+1
Step 5:
if(i>mid)
while(j<=high)
b[k] a[j]
j j+1
k k+1
Else
while(i<=mid)
b[k] a[i]
i i+1
k k+1
step 6: Exit
Data Structure
Example:
5,2,4,7,1,3,2,6
Data Structure
Step 2:-
Data Structure
Step 3:-
Now we compare the value stored at location 4, with the value being
searched, i.e., 31. We find that the value at location 4 is 27, which is not a
match.
As the value to be searched is greater than 27 and we have a sorted array,
so we also know that the target value must be in the upper portion of the
array.
We change our low to mid + 1 and find the new mid value again. low =
mid + 1
mid = (low + high ) / 2
Here it is, (5 + 9) / 2 = 7
Our new mid is 7 now. We compare the value stored at location 7 with our
target value 31.
The value stored at location 7 is not a match, rather it is more than what
we are looking for. So, the value must be in the lower part from this
location.
Data Structure
Hence, We change our low to mid -1 and find the new mid value again.
low = mid + 1
mid = (low + high) / 2
Here it is, (5 + 6) / 2 = 5 (integer value of 5.5). So, 5 is the mid of the array.
Step 1:[Initialization]
low ← 0
high ← n-1
flag ←1
Step 2:
while(low <= high)
repeat step 3 to 4
Step 3:
mid = (low+high)/2
Step 4:
if (x < List[mid])
then high = mid-1
else if (x > List[mid])
then low= mid+1
else if(x = List[mid])
then
write(“Search is successful at location : mid+1)
flag ← 0
exit
Step 5:
if ( flag = 1)
then Write(“Search is unsuccessful”)
Step 6:[Finished]
exit
Algorithm : SEQUENTIAL_SEARCH(List, n, x)
List : Array
n : Size of Array
x : Element to be searched
Step 1: [Initialization]
Data Structure
i←0
flag ←1
Step 2:
repeat step 3 for i = 0, 1, 2, … , n-1
Step 3:
if(x = List[i])
then write(“Search is successful at location : i + 1”)
flag ← 0
exit
Step 4:
if (flag =1)
then Write(“Search is unsuccessful”)
Step 5: [Finished]
exit