All - Units - Data Structures
All - Units - Data Structures
Data Structure
The organized collection of data in a mathematical or logical way is called Data Structure.
OR
A way of storing and organizing data in a computer is called data structure.
Classification of Data Structure:
Data
Structure
float Graphs
Linked List
Double
Stack
Queue
Primitive Data Structure: A data structure can be manipulated by machine level instructions
is called primitive data structure. Example: int, float, char, double, long etc.
Non-Primitive Data Structure: A data structure which cannot be manipulated directly by
machine level instructions is called non-primitive data structure. They are two types:
1. Linear Data Structure
2. Non-linear Data Structure
Linear Data Structure: A Data Structure which stores all the elements sequentially in memory
is called linear Data Structure. Example: Array, Linked List, Stack and Queue.
Array: It is a definite collection of homogenous elements that can be stored sequentially.
Example: int A[3];
Memory representation of an array
101 102 103 104 105 106 107 108
50 60 70 80 NULL
The types of linked list are:
1. Singly List
2. Doubly List
3. Circular List
Stack: It is a linear data structure, the data can be inserted and deleted at one end is known
TOP. Stack works in the fashion of LIFO.
C top
B
A
Queue: Queue is a linear data structure which has two ends. One end is used to insert the
element named as REAR and the other end is used to delete the element named as FRONT.
FRONT REAR
A B C D E F G
Non-Linear Data Structure
Data structures where data elements are arranged sequentially or linearly are called non-linear
data structures. Example: Tree, Graph.
Tree: It is a finite set of nodes or vertices each tree has a root node and remaining nodes are
considered as leaf nodes or sub trees.
B C
D E
B C
Ceil function provides the smallest integer that is greater or equal to the given value.
The symbol for ceil function is ⌈ ⌉
Example x=4.678
⌈𝒙⌉ = 5
2. Modular function or remainder function
If x is an integer and m is a positive integer then x(mod m) gives the integer remainder.
Example x=25 and m=3
25 (mod 3)
=1
3. Integer function
If x is a real number the integer function int(x) returns the integer value and it truncates
the fractional part.
Example INT(45.98)
=45
INT(-900.456)
=-900
4. Absolute function
The function ABS(x) gives the absolute value of x, which means it gives +ve value of
x even if it is -ve.
Example x= - 900 x=500
ABS(x)=900 ABS(x)=500
5. Summation
Consider a sequence of terms 𝒂𝟏 + 𝒂𝟐 + 𝒂𝟑 + ⋯ + 𝒂𝒏 and it is denoted by ∑𝟏≤𝒊≤𝒏 𝒂𝒊
6. Factorial Function
The product of positive integers from one to n (1 to n) is called 𝑛!
𝑛! = 1 × 2 × 3 × … … … .× 𝑛 − 1 × 𝑛
7. Permutation
A permutation is a set of arrangement of elements of the set in some order.
Eg: LOW
The possibilities of arrangement is LOW, LWO, OLW, OWL, WLO, WOL
8. Exponents & Logarithms
Exponent means how many times a number is multiplied by itself if a is the base m is
an exponent.
Eg: 23 = 2 × 2 × 2
Logarithm: If B is a positive number then the logarithm of positive integer, x to the
base b is written as log 𝑏 𝑥
9. Algorithmic Notation
Algorithm: It is a step by step procedure to perform a particular task
ARRAY
Array
It is a collection of element of same datatype.
Or
Operation on Array
1. Traversal: processing each element in array
2. Insertion: Adding a new element in array
3. Deletion: Deleting an element from the array
4. Search: find the location of the given element
5. Sorting: Arranging the elements in some order
6. Merging: combining two arrays into one array
1. Traversal
It means accessing all elements in the array.
Algorithm
TRAVERSE( )
1. Start the program
2. Repeat I = LB to UB
Process a[ I ]
End Loop
3. Stop the program
Here a is the array, LB is the lower bound and UB is the upper bound we process all the
elements of array using loop.
Example
# include<stdio.h>
void main()
{
int a[ ]={10, 20, 30, 40 }
for(int i=0; i<4; i++)
printf(“%d\t”, a[i]);
}
Output
10 20 30 40
2. Insertion
Inserting an element means to add an element in the array.
Algorithm
INSERT(A, N, LOC, ITEM )
1. Read the array, N value, LOC to insert at position, ITEM to insert
2. Initialize I=N
3. Repeat while( I >= LOC )
Set A[ I + 1 ]=A[ I ]
Set I= I – 1
End loop
4. Insert the element at the position by A[ LOC ] = ITEM
5. Increment N by 1, N = N + 1
6. End of the program
Here A is an array, N is the number of elements in the array, LOC is the position to insert an
element, ITEM is the element to be inserted. To create the space for the new item, move the
element of A by 1 up to the space created. Then insert the new item using A[ LOC ] = ITEM
and increment the size of the array by 1 by using N = N + 1
void INSERT(int A[],int n) // A is the array and n is the size of the array
{
int LOC,ITEM,i;
printf(“\n Enter the location where you wish to insert an element: “);
scanf(“%d”,&LOC);
if(LOC >= n+1)
printf(“\n Insertion is not possible.\n”);
else
{
printf(“ \nEnter the value to insert: ”);
scanf(“%d”, &ITEM);
for(i=n-1;i>=LOC-1;i--)
A[i+1] = A[i];
A[LOC-1] = ITEM;
n= n+1;
}
}
4. Deletion
Deleting an element means removing an element from the array.
Algorithm
DELETE(A, N, LOC, ITEM )
1. Read the array, N value, LOC is the location to delete, ITEM to delete
2. Set ITEM=A[ LOC ] and delete the ITEM
3. Repeat for I= LOC to N
Set A[ I ] = A[ I + 1 ]
End for
4. decrement N by 1, N = N – 1
5. End of the program
Here A is an array, N is the number of elements in the array, LOC is the position to delete an
element, ITEM is the element to be delete. Assign ITEM= A[LOC ] and delete the data. Then
left shift one value in the array until the size of the array is reached and+ decrement the size of
the array by 1
void DELETE(int A[],int n) // A is the array and n is the size of the array
{
int LOC,ITEM,i;
printf(“\n Enter the location where you wish to delete an element: “);
scanf(“%d”,&LOC);
if(LOC >= n+1)
printf(“\n Deletion is not possible.\n”);
else
{
for(i=LOC-1;i<n-1;i++)
A[i] = A[i+1];
A[LOC-1] = ITEM;
n= n-1;
}
}
5. Searching.
It refers to finding an element in an array.
Linear Search
It is also known as sequential search. It searches all the elements sequentially in list. If the
element is present in the list it print the element is found at index position, otherwise it return
-1(not found).
Algorithm:
LINEAR SEARCH(A, N, KEY)
Set I=0
While ( I <= N ) do
If A[ I ]= = KEY then
Return I
End Loop
Return -1
This algorithm sets the index value I as 0 initially it checks all the elements in the array
sequentially. If the array element is equal to the KEY then it print the location by using the I
value otherwise it return -1.
Complexity of linear search
For worst case it takes ‘O(n)’ comparisons
int linear_search(int item,int array[100],int n)
{
int i;
for(i=0;i<n;i++)
{
if(item == array[i])
{
return i+1;
}
}
return -1;
}
Binary Search
Binary Search follows the divide and conquer approach. The list must be in sorted manner.
The following algorithm
Algorithm:
BINARY SEARCH ( A, N, ITEM)
Read the Array A, the size of the array N, the ITEM to be searched
Initialize FIRST = 0, LAST= N-1, MID= (FIRST+LAST)/2
While (FIRST<=LAST)
if (ITEM == A[MID] )
return MID+1
else if ( ITEM < A[MID] )
LAST= MID – 1
Else
FIRST= MID + 1
End while
Return -1
The required entry is first compared with the middle element. If the match is found then, the
location of the middle element is returned. Otherwise, if the middle element is greater than the
search element then it searches the second half of the array. If the search element is less than
the middle element then it searches the first half of the array. This is repeated until the search
element is found otherwise not found.
int binary_search(int item,int array[100],int n)
{
int mid,first,last;
first = 0;
last = n-1;
mid = (first + last)/2;
while(first<=last)
{
if(item == array[mid])
{
return mid +1;
}
else if(item <= array[mid])
{
last = mid+1;
mid = (first+last)/2;
}
else
{
first = mid+1;
mid = (first+last)/2;
}
}
return -1;
}
Complexity of binary search
For worst case it takes ‘’ comparisons
Sparse matrix
Matrix which contain more number of zero entries than non-zero entries is called sparse
matrix.
𝟎 𝟎 𝟕 𝟎 𝟎 𝟓
𝟏 𝟎 𝟎 𝟎 𝟎 𝟎
Example 𝟎 𝟎 𝟎 𝟎 𝟗 𝟎
𝟎 𝟎 𝟎 𝟎 𝟎 𝟖
[𝟎 𝟎 𝟑 𝟎 𝟎 𝟎]
The above matrix contains 30 entries but it contains only 6 non-zero entries. This matrix takes
60 bytes to store the data. Even it has only 6 non-zero element. So, represent a new matrix for
storing non-zero present in the above matrix.
Row Column Value
1 3 7
1 6 5
2 1 1
3 5 9
4 6 8
5 3 3
The following program accepts a matrix as input and prints the 3-tuple representation of it.
#include <stdio.h>
#include <conio.h>
void main()
{
int a[10][10], row, col, i, j;
printf(“Enter the order of the matrix:”);
scanf(“%d%d”, &row, &col);
printf(“\nEnter the elements of the matrix:”);
for(i=0;i<row;i++)
for(j=0;j<col;j++)
scanf(“%d”,&a[i][j]);
printf(“The 3-tuple representation of the matrix :\n”);
for(i=0;i<row;i++)
for(j=0;j<col;j++)
{
if(a[i][j]!=0)
{
printf(“%d\t%d\t%d”,(i+1),(j+1),a[i][j]);
}
}
}
Output
Enter the order of the matrix: 5 5
Enter the elements of the matrix:
𝟎 𝟎 𝟎 𝟎 𝟖
𝟏 𝟎 𝟎 𝟎 𝟎
𝟎 𝟎 𝟗 𝟎 𝟎
𝟎 𝟎 𝟎 𝟎 𝟎
𝟎 𝟎 𝟔 𝟎 𝟎
Enter the elements of the matrix:
1 5 8
2 1 1
3 3 9
5 3 6
Asymptotic notations
• It is the mathematical way of representing the time complexity of an algorithm.
• Following asymptotic notations are used to calculate the running time complexity of
an algorithm.
• O − Big Oh – upper bound
• Ω − Omega – lower bound
• θ − Theta- average bound
Big Oh Notation
• This method is used to find the upper bound of an algorithm’s running time.
• It is the worst case time complexity of an algorithm.
Definition: The function f(n) = O(g(n)) if and only if there exists a positive constants c and
n0 such that f(n)<=c*g(n) for all n>=n0
The following figure represents Big oh Notation
Chapter 2
Linked List
Linked list is a linear collection of data elements called nodes. Each node is divided into 2
fields. The first part is for info or data field and second part for pointer or link field to the
next node. The general representation is
INFO LINK
Where INFO is used to store the data value, LINK is used to store the address of next node.
Example:
START
5 8 3 NULL
Here START is an external pointer it stores the address of the first node. NULL indicates it is
the end of linked list.
Advantages of Linked List
struct node
{
int info;
struct node *link;
};
It is a self-referential structure in C. Here link is the pointer that points the next data of same
structure.
Types of Linked List
Linked List are classified into 5 types:
INFO LINK
The second step get the data item and place in INFO field
START
50
INFO LINK
The third step place NULL value in Link fields
START
50 NULL
INFO LINK
The fourth step will return to main program.
Traversal
The process of visiting all nodes in Linked List is known as traversing. The following algorithm
traverse the Linked List
Algorithm
1. Is list is empty?
If(START==NULL)
Display “Linked list is empty”
Return
End if
2. Assign start value to CURPTR
CURPTR=start
3. Repeat while (CURPTR != NULL)
Print CURPTR→INFO
CURPTR=CURPTR→LINK
4. Return
Example
Consider a Linked List with 3 nodes are as shown below:
START
2002 2002 2015 198
10 58 24 NULL
Insertion
This operation is used to insert a new node in the Linked List. The new node can be inserted in
3 ways:
1) Insert at the beginning of a Linked List
2) Insert at the end of a Linked List
3) Insert at the specified position in Linked List
1) Insert at the beginning of a Linked List
The following algorithm insert a node at the beginning.
Algorithm:
1. Create a node using malloc
NEWNODE=(NODE*) malloc(sizeof (NODE))
2. Store the data
NEWNODE→INFO=ITEM
3. Assign the start value to the link of NEWNODE
NEWNODE→LINK=start
4. Assign NEWNODE as START
Start=NEWNODE
5. Exit
Explanation
Consider the following linked list contain 3 nodes
START
2010 2010 215 1003
10 90 24 NULL
2025
NEWNODE=2025
The second step stores data in INFO field
2025
50
The third step assign NEWNODE link to START
2025
50 2010
START
2010 2010 215 1003
10 90 24 NULL
The following code illustrates inserting a node in the beginning of the Linked List
void insert_begin()
{
struct node *temp;
temp=(struct node *)malloc(sizeof(struct node));
if(temp==NULL)
{
printf("\nOut of Memory Space\n");
return;
}
printf("\nEnter the data value for the node:" );
scanf("%d",&temp->info);
temp->next =NULL;
if(start==NULL)
{
start=temp;
}
else
{
temp->next=start;
start=temp;
}
}
The first step check START is NULL, if it is NULL it call Insert at beginning otherwise
it assign Start value to CURPTR
The third step is traverse to point the last node
START
2010 2010 215 1003
10 90 24 NULL
2025
NEWNODE=2025
The fifth step stores data in INFO field
2025
50
The sixth step assign NEWNODE link to CURPTR → LINK and NEWNODE → LINK
= NULL. The pictorial representation is
START
2010 2010 215 1003 2025
10 90 24 50 NULL
The following code illustrates inserting a node at the end of the Linked List
void insert_end()
{
struct node *temp,*ptr;
temp=(struct node *)malloc(sizeof(struct node));
if(temp==NULL)
{
printf("\nOut of Memory Space\n");
return;
}
printf("\nEnter the data value for the node:" );
scanf("%d",&temp->info );
temp->next =NULL;
if(start==NULL)
{
start=temp;
}
else
{
ptr=start;
while(ptr->next !=NULL)
{
ptr=ptr->next ;
}
ptr->next =temp;
}
}
2025
NEWNODE=2025
In fifth step it assigns INFO Value to NEWNODE
2025
50
In sixth step it creates link between CURPTR and NEWNODE. Consider pos is 2.The
pictorial representation is as follows.
START
2010 2010 2025 215 1003
10 50 90 24 NULL
The following code illustrates inserting a node at a specific position of the Linked List
void insert_pos()
{
struct node *ptr,*temp;
int i,pos;
temp=(struct node *)malloc(sizeof(struct node));
if(temp==NULL)
{
temp->next=NULL;
if(pos==0)
{
temp->next=start;
start=temp;
}
else
{
for(i=0,ptr=start;i<pos-1;i++)
{
ptr=ptr->next;
if(ptr==NULL)
{
printf("\nPosition not found\n");
return;
}
}
temp->next =ptr->next ;
ptr->next=temp;
}
}
DELETION
This operation is used to delete a node from the Linked List. A node can be deleted using three
ways:
1) Delete a node from the beginning of a Linked List
2) Delete a node from end of a Linked List
3) Delete a node from a specified position in Linked List
1) Delete a node from the beginning of a Linked List
This operation deletes a node from the beginning of Linked List.
Algorithm
1. Is List is Empty?
if (START= = NULL)
print “List is Empty”
else
go to step 2
2. Assign Start value to CURPTR
CURPTR = Start
3. Assign Link field of CURPTR to Start
The first step check Start is NULL. If it is print list is empty otherwise step2
In second step assign CURPTR by Start (Here Start = 2002 therefore, CURPTR= 2002)
In third step set the CURPTR → LINK to Start
In fourth step free the CURPTR
The pictorial representation after deletion is
START
2015 2015 198
58 24 NULL
The following code illustrates delete a node from the beginning of the Linked List
void delete_begin()
{
struct node *ptr;
if(ptr==NULL)
{
printf("\nList is Empty\n");
return;
}
else
{
ptr=start;
start=start->next ;
printf("\nThe deleted element is : %d",ptr->info);
free(ptr);
}
}
The first step check Start is NULL. If it is print list is empty otherwise step2
In second step it check is list contain one element if it is set Start is NULL otherwise
step4
In third step delete start
In fourth step Assign start to CURPTR
In fifth step set PREPTR to NULL
In sixth step traverse the list until CURPTR points the last node.
In seventh step delete CURPTR
In eight step set PREPTR → LINK as NULL
START
2002 2002 2015
10 58 NULL
The following code illustrates delete a node from end of the Linked List
void delete_end()
{
struct node *temp,*ptr;
if(start==NULL)
{
printf("\nList is Empty\n");
exit(0);
}
else if(start->next ==NULL)
{
ptr=start;
start=NULL;
printf("\nThe deleted element is: %d",ptr->info);
free(ptr);
}
else
{
ptr=start;
while(ptr->next!=NULL)
{
temp=ptr;
ptr=ptr->next;
}
temp->next=NULL;
printf("\nThe deleted element is: %d",ptr->info);
free(ptr);
}
}
Explanation
Consider a Linked List with 3 nodes are as shown below:
START
2002 2002 2015 198
10 58 24 NULL
The first step check POS= = 1 if it call delete_beginning otherwise goto step2
In second step Assign start to CURPTR
In third step set PREPTR to NULL
In fourth step CURPTR as specified position using loop.
In fifth step set link between PREPTR and next node of CURPTR. Then delete the
CURPTR.
The following code illustrates delete a node from a specific position of the Linked List
void delete_pos()
{
int i,pos;
struct node *temp,*ptr;
if(start==NULL)
{
printf("\nThe List is Empty\n");
exit(0);
}
else
{
printf("\nEnter the position of the node to be deleted:");
scanf("%d",&pos);
if(pos==0)
{
ptr=start;
start=start->next ;
printf("\nThe deleted element is: %d",ptr->info );
free(ptr);
}
else
{
ptr=start;
for(i=0;i<pos;i++)
{
temp=ptr;
ptr=ptr->next ;
if(ptr==NULL)
{
printf("\nPosition not Found\n");
return;
}
}
temp->next =ptr->next ;
printf("\nThe deleted element is:%d",ptr->info );
free(ptr);
}
}
}
Length
This operation is used to find the number of nodes in Linked List
Algorithm
1. Initialize len=0
2. If (Start = = NULL)
{
Print “List is Empty”
Return
}
3. Set CURPTR=Start
4. while(CURPTR != NULL)
{
len++
CURPTR= CURPTR → LINK
}
5. return len
Explanation
Consider a Linked List with the following nodes:
START
2002 2002 2015 198
10 58 24 NULL
In the first step it initializes the variable len as 0
In the second step it checks whether the Start is NULL , Here Start =2002
In the third step it assigns the Start value to CURPTR that is CURPTR =2002
In the fourth step it checks CURPTR is NULL if it is not then it increment Len value by 1
and set CURPTR= CURPTR → LINK. Repeat until CURPTR is NULL
In fifth step it returns len value , Here len=3
Searching
In circular linked list, only one pointer is used for insertion and deletion.
Circular linked list contains the following operations
i. Creation
ii. Insertion
iii. Deletion
iv. Traversal
v. Searching
vi. Sorting
The following program creates a node in circular linked list and display its data.
#include<stdio.h>
#include<conio.h>
#include<ctype.h>
struct node
{
int INFO;
struct node *LINK;
};
typedef struct node NODE;
NODE *last=NULL;
void create_clist()
{
char ch;
int i=0;
NODE *NEWNODE;
NEWNODE=(NODE*)malloc(sizeof(NODE));
last=NEWNODE;
NEWNODE →LINK=last;
while(1)
{
printf("\n Enter the node %d",i+1);
scanf("%d",&NEWNODE→INFO);
printf("Do you wish to add one more node (Y/N): \n");
ch=getche();
if(toupper(ch)=='Y')
{
NEWNODE=(NODE*) malloc(sizeof(NODE));
NEWNODE→LINK=last→LINK;
last→LINK=NEWNODE;
last=NEWNODE;
i++;
}
else
break;
}
}
void display()
{
NODE *CURPTR;
if(last= = NULL)
{
printf("List is Empty \n");
return;
}
CURPTR=last→LINK;
printf("\n");
while(CURPTR!=last)
{
printf("%d",CURPTR→INFO);
printf("→");
CURPTR=CURPTR→LINK;
}
printf("%d",last→INFO);
}
void main()
{
clrscr();
printf("\nCircular Linked List Demonstration\n");
create_clist();
display();
getch();
}
OUTPUT
Circular Linked List Demonstration
Enter the node 1
50
Do you wish to add one more node (Y/N): Y
Enter the node 2
45
Do you wish to add one more node (Y/N): Y
Enter the node 3
67
Do you wish to add one more node (Y/N): N
50-->45-->67
• INFO
• BACK
• FORW
The INFO field stores the data and the BACK field stores the address of the previous node and
the FORW field stores the address of the next node.
The node in doubly linked list is represented below:
NODE *start=NULL;
void create_dlist()
{
char ch;
int i=0;
NODE *NEWNODE, *CURPTR;
CURPTR=(NODE*)malloc(sizeof(NODE));
start=CURPTR;
CURPTR →FORW=NULL;
CURPTR →BACK=NULL;
while(1)
{
printf("\n Enter the node %d",i+1);
scanf("%d",&CURPTR→INFO);
printf("Do you wish to add one more node (Y/N): \n");
ch=getche();
if(toupper(ch)=='Y')
{
NEWNODE=(NODE*) malloc(sizeof(NODE));
CURPTR→FORW=NEWNODE;
NEWNODE→BACK=CURPTR;
NEWNODE→FORW=NULL;
CURPTR=NEWNODE;
}
else
{
CURPTR →FORW=NULL;
break;
}
i++;
}
}
void display()
{
NODE *CURPTR =start;
if(start= = NULL)
printf("List is Empty \n");
else
{
printf("\n");
while(CURPTR!=NULL)
{
printf("%d",CURPTR→INFO);
printf("→");
CURPTR=CURPTR→FORW;
}
printf("NULL");
}
}
void main()
{
clrscr();
printf("\nDoubly Linked List Demonstration\n");
create_dlist();
display();
getch();
}
OUTPUT
Doubly Linked List Demonstration
Enter the node 1
50
Do you wish to add one more node (Y/N): Y
Enter the node 2
45
Do you wish to add one more node (Y/N): Y
Enter the node 3
67
Do you wish to add one more node (Y/N): N
50→45→67→NULL
Advantages of Doubly Linked List
1. It can be traversed in forward and backward direction
2. Insertion and deletion are easy because every node has forward and backward link
3. It is used to represent the trees effectively
4. This simplifies list management
Disadvantages of Doubly Linked List
1. Extra memory is required to store the back pointer.
2. Extra effort is required to deal with the extra link.
Header Linked List
• A special node in the beginning of the list is known as header node.
• This node does not contain actual data but contains useful information about the entire
linked list such as total number of nodes, pointer to the last node etc.
• The start points to the header node in the header linked list.
• Link field of header node points the first node in the list.
• The header linked list will always contain a header node even if list is empty.
Header linked list are of two types:
STACK
Definition
Stack is a collection of homogeneous data items where the insertion and deletion operations
take place at one end called TOP of the stack. Stack works on LIFO (Last In First Out) Fashion
5 TOP
8
1
StackADT
A set of stack data member and a set of stack operations that perform on stack data. The
stack data members are TOP, MAXSTK. The stack operations such as
1. Createstack()- Create stack with n elements.
2. push()- push an element on to the TOP of the stack
3. pop()- POP an element from the TOP of the stack.
4. Isempty()- returns true if the stack is empty otherwise false
5. Traverse()- accessing all the elements in the stack.
6. Count()- count the number of elements in the stack.
PUSH operation
It is used to insert an element on the TOP of the stack. If stack is full, PUSH operation is not
possible.
Algorithm: PUSH(S,TOP, MAXSTK, item)
1. check Stack is overflow
if TOP= = MAXSTK - 1 then
print "Stack Overflow"
return
2. Increment TOP value
TOP=TOP+1
3. Insert the item at the TOP
S[TOP]=item
4. return
Explanation
Consider the following stack contain 3 element and its MAXSTK value is 5
5 TOP
8
1
TOP
5
8
1
10 TOP
5
8
1
4. return
POP operation
This operation deletes an element from the stack i.e., it deletes the TOP element from the stack.
If stack is empty the pop operation is not possible.
Algorithm: POP(S,TOP, item)
1. Check underflow
if TOP== -1 then
print "stack underflow"
return
2. Delete the item
item=S[TOP]
3. Decrement TOP value
TOP=TOP-1
4. return
Explanation
Consider a stack contain 3 elements and its MAXSTK value is 5.
5 TOP
8
1
1. Check stack is underflow or not, here TOP=2and MAXSTK=5. Therefore, go to step 2
TOP
8
1
8 TOP
1
4. Return
Traverse operation
Accessing all elements in the stack is known as traversal operation.
Algorithm: DISPLAY(S, TOP)
1. Check underflow
if TOP== -1 then
print "stack underflow"
return
2. Access all elements using loop
for i=TOP to 0
print S[i]
end for
3. return
Explanation
Consider a stack contain 3 elements and its MAXSTK value is 5.
5 TOP
8
1
Advantages of Recursion:
1. Reduces the complexity of the problem
2. It allows user to write simple and elegant program
3. Programs are smaller in length
4. Programs can have any no. of nesting levels
5. Top-Down Programming model
Recursion : Example 1 - Finding factorial using Recursive method
1 𝑖𝑓 𝑁 = 0
FACTORIAL(N) = { }
𝑁 ∗ 𝐹𝐴𝐶𝑇𝑂𝑅𝐼𝐴𝐿 (𝑁 − 1) 𝑖𝑓 𝑂𝑡ℎ𝑒𝑟𝑤𝑖𝑠𝑒
Algorithm: FACTORIAL(N)
Step 1: if (N= = 0) then
fact=1
Step 2: else
Fact=N * FACTORIAL (N-1)
End if
Step 3: return(fact)
Step 4: Stop
Consider the following represents 4! Using recursive function
4!=4*3!
3!=3*2!
2!=2*1!
1!=1*0!
1!=1
2!=2
3!=6
4!=24
The whole process is implemented in the stack as shown below
0 𝑖𝑓 𝑁 = 0 𝑜𝑟 𝑁 = 1
Fib(N)={ 1 𝑖𝑓 𝑁 = 2 }
𝑓𝑖𝑏(𝑁 − 1) + 𝑓𝑖𝑏(𝑁 − 2) 𝑖𝑓 𝑁 > 2
Algorithm: fibon(N)
if(N==0) || (N==1) then
fib=0
else if (N==2) then
fib=1
else if (N>2) then
fib=fibon(N-1) +fibon(N-2)
end if
return fib
stop
Algorithm Steps
fibon(6)=fibon(5)+fibon(4)
fibon(5)=fibon(4)+fibon(3)
fibon(4)=fibon(3)+fibon(2)
fibon(3)=fibon(2)+fibon(1)
fibon(2)=1, fibon(1)=0
fibon(3)=1
fibon(4)=2
fibon(5)=
3
fibon(6)=5
Algorithm: move(n, S, T, D)
{
move(n-1, S, D, T) //move (n-1) disks from S to T
move(1, S, T, D) //move 1 disk from S to D
move(n-1, T, S, D) //move (n-1) disks from T to D
}
Consider the Tower of Hanoi has three disks (n=3)
Push()
( (
Push()
( ( (
1 ( (
+ ( (
2 ( (
Pop()
) (
* (
3 (
Pop()
)
Example
Consider the following expression Q=A + (B + C)
To covert infix to postfix push a ‘(‘ on to the stack and add a ‘)’ at the end of the infix
expression
Q= A + (B + C))
Line Scanned Stack Postfix Expression
Symbol
A A
1 (
+ A
2 ( +
3 ( A
( + (
B AB
4 ( + (
+ + AB
5 ( + (
C + ABC
6 ( + (
) ABC+
7 ( +
) ABC++
8
Push Operation
The push operation is used to insert an element into the stack. The new element is added at the
topmost position of the stack.
Algorithm: PUSH()
step 1: Allocate memory for the new node and name it as NEWNODE
step 2: set NEWNODE→ INFO = ITEM
step 3: if TOP= = NULL
set NEWNODE→ LINK = NULL
set TOP= NEWNODE
else
set NEWNODE→LINK= TOP
set TOP= NEWNODE
end if
step 4: End
Consider the linked stack as shown below:
TOP
2025 2025 2010 215
50 10 90 NULL
To insert an element with value 80, we first check if TOP= = NULL, then we allocate memory
for a new node, store the value 80 in its INFO part and NULL in its LINK part. We add the
new node at the beginning of the linked stack.
The updated linked stack is shown below:
TOP
1020 1020 2025 2010 215
80 50 10 90 NULL
Pop operation
The pop operation is used to delete the topmost element from a stack.
Algorithm: POP()
Step 1: If TOP= = NULL
print "UNDERFLOW"
go to step 5
end if
Step 2: set PTR= TOP
Step 3: set TOP= TOP→NEXT
Step 4: free PTR
Step 5: End
Consider the linked stack as shown below:
TOP
2025 2025 2010 215
50 10 90 NULL
Before deleting the values, we first check TOP = = NULL if so, the stack is empty otherwise
it deletes a value from a stack
TOP
2010 2010 215
10 90 NULL
QUEUE
Queue is defined as an ordered collection of items from which, the items may be deleted at one
end called FRONT end and the items may be inserted at the other end called REAR end.
Queue works on FIFO (First In First Out) fashion.
Classification of Queue
Queue
Linear Queue
It is also known as sequential queue. It is implemented using linear array or linear list. This
linear queue is represented using linear array with 2 variables FRONT & REAR.
0 1 2 3 4 5 6 7
26 9 23 34 45 67 45 34
FRONT REAR
Deletion Insertion
Queue ADT
A collection of queue data members and queue operations that preform on queue data. The data
members or variables are FRONT and REAR. Queue operations such as
1. Create()- Create queue with n elements.
2. Insert()- insert an element at the end of the queue
3. Delete()- delete an element from the beginning of the queue.
4. Isempty()- returns true if the queue is empty otherwise false
5. Traverse()- accessing all the elements in the queue.
6. Count()- count the number of elements in the queue.
Insertion()
This operation inserts an element on the end of a queue. If queue is full, insertion is not possible.
Algorithm: Qinsert(Q, FRONT, REAR, N, item)
Step 1: check overflow
if REAR= = N-1 then
print “Overflow”
return
Step 2: Increment REAR pointer
REAR= REAR+1
0 1 2 3 4 5 6 7
26 9 23 34 45
FRONT REAR
1. Check queue overflow condition if it is print overflow. Here, REAR=4 so it is false.
2. Increment REAR=REAR + 1
0 1 2 3 4 5 6 7
26 9 23 34 45
FRONT REAR
3. Insert the item
Q[REAR]= item i.e., Q[5]=86
0 1 2 3 4 5 6 7
26 9 23 34 45 86
FRONT REAR
4. Return
The following C function illustrates Queue insertion
void Qinsert()
{
if(REAR == N-1)
printf("\n Queue Overflow");
else
{
printf("\n Enter an item:");
scanf("%d", &item);
REAR++;
QUEUE[REAR]= item;
}
}
Deletion
This operation deletes an item from the beginning of the queue. If Queue is Empty, deletion
operation is impossible.
Algorithm: Qdelete(Q, FRONT, REAR, N, item)
Step 1: Check underflow
if REAR= = FRONT-1 then
print "Underflow"
return
Step 2: Delete the item
item = Q[FRONT]
Step 3: if FRONT= = REAR
FRONT=0, REAR=-1
else
FRONT=FRONT+1
`Step 4: return
Explanation
Consider a queue contain 5 elements and Max is 8
0 1 2 3 4 5 6 7
26 9 23 34 45
FRONT REAR
1. Check queue is underflow. Here, FRONT=0 and REAR=4, so it is false
2. Delete the item. i.e., item= Q [0]⟹item =26
0 1 2 3 4 5 6 7
9 23 34 45
FRONT REAR
3. Check FRONT and REAR value is equal. Here FRONT=0 and REAR =4. So, it is
false, increment FRONT=FRONT+1
0 1 2 3 4 5 6 7
9 23 34 45
FRONT REAR
4. Return
The following C function illustrates Queue deletion
void Qdelete()
{
if (REAR= = FRONT - 1)
printf("\nQueue Underflow");
else if(REAR= = FRONT)
{
printf("This is the last element in the Queue");
printf("\n The Last element deleted is : %d", QUEUE[FRONT]);
FRONT=0;
REAR=-1;
}
else
{
printf("\n Deleted item is %d", QUEUE[FRONT]);
FRONT++;
}
}
Qempty Operation
This operation returns true if the queue is empty otherwise false.
A Queue is empty only when REAR=-1 and FRONT=0
The following function check Queue is empty
int Qempty()
{
if(REAR= = FRONT-1)
return 1;
else
return 0;
}
Qfull Operation
This operation returns true, if the queue is full otherwise false. A Queue is full only when
REAR== N-1. The following function check Queue is full.
int Qfull()
{
if(REAR= = N-1)
return 1;
else
return 0;
}
Traversal operation
This operation access all the elements in the queue.
Algorithm: Qdisplay(Q, FRONT, REAR, N)
Step 1: Check underflow
if REAR== FRONT-1 then
print "Underflow"
return
Step 2: Repeatedly access the queue elements
for (i=FRONT; i<= REAR; i++)
print Q[i];
Step 3: return
Explanation
Consider the following Queue Max Size is 8 and it contain 5 elements.
0 1 2 3 4 5 6 7
26 9 23 34 45
FRONT REAR
1. Check underflow, here REAR=4, FRONT=0 so it is false therefore Go to step 2
2. Repeatedly print the value of Queue 26 9 23 34 45
3. Return
Linked Representation of Queues
In linked list implementation, every queue element has two parts, one that stores the
data and the other that stores the address of the next element.
The FRONT pointer points the first element and the REAR pointer points the last
element.
All insertions will be done at the REAR end and all insertions at the FRONT end
FRONT = REAR = NULL indicates the queue is empty
Insert Operation
The insert operation is used to insert an element into a queue. The new element is added as
the last element of the queue.
Algorithm: QINSERT()
Step 1: Allocate memory for the new node and name it as NEW_NODE
Step 2: Set NEW_NODE → INFO=item
Step 3: If FRONT = NULL
Set FRONT=REAR=NEW_NODE
Set FRONT→ LINK = REAR→ LINK =NULL
Else
Set REAR→> LINK=NEW_NODE
Set REAR = NEW_NODE
Set REAR→NEXT=NULL
End if
Step 4: END
Consider the following figure shows linked queue.
FRONT REAR
Delete Operation
The delete operation is used to delete the FRONT element from the queue.
Algorithm QDELETE()
Step 1: If FRONT = NULL
Print "Underflow"
goto Step 5
Step 2: Set PTR = FRONT
Step 3: Set FRONT = FRONT → LINK
Step 4: Free PTR
Step 5 End
Consider the linked Queue as shown below:
FRONT REAR
Before deleting the values, we first check FRONT = = NULL if so, the queue is empty
otherwise it deletes a value from a queue.
FRONT REAR
CIRCULAR QUEUE
Circular Queue is a linear data structure in which the operations are performed based on FIFO
(First In First Out) principle and the last position is connected back to the first position to make
a circle. It is also called ‘Ring Buffer’. The representation of circular queue is shown below:
Insert Operation
This operation inserts an element on the REAR position of a queue. If queue is full, insertion
is not possible.
Algorithm CQINSERT(Q,FRONT,REAR,N,ITEM)
Step 1: If FRONT == (REAR+1) %N
display “overflow”
Step 2: IF FRONT == -1
FRONT = REAR = 0
Step 3: ELSE REAR = (REAR + 1)%N
Step 4: Q[REAR] = ITEM
Step 5: END
Delete Operation
This operation deletes an item from the FRONT position of the queue. If Queue is Empty,
deletion operation is impossible.
Algorithm QDELETE (Q, FRONT, REAR, N, ITEM)
Step 1: If FRONT == -1
Write “underflow”
Return
Step 2: ITEM = Q[FRONT]
Step 3: IF FRONT = REAR
FRONT = REAR = -1
ELSE
FRONT = (FRONT + 1)%N
Step 4 : END
The following figure illustrates insertion and deletion of a queue
PRIORITY QUEUE
A priority queue is a queue such that element of the queue has been assigned with a
priority such that the order in which elements are processed comes from the following
rules:
o An element of higher priority is processed before any element of lower
priority
o If two elements have same priority, then the element which come first will be
processed first.
Types of priority queue
There are two types of priority queue. They are:
Priority Queue
In Deque or Double Ended Queue, insertion and deletion can be done from both ends of
the queue either from the front or rear.
Types of DEQUE
The 2 variations of deque is as follows:
Operations on Deque:
The basic operations are:
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.
Consider an input restricted deque and now we can add element only on the REAR side of the
queue but we can delete from both sides.
Applications of Queues:
Queues are used as waiting lists for a single shared resource like printer, disk, CPU.
Queues are used as buffers in most of the applications like MP3 media player, CD
player, etc.
Queue are used to maintain the play list in media players in order to add and remove
the songs from the play-list.
Queues are used in operating systems for handling interrupts.
Trees
Definition:
ii)the remaining nodes are partitioned into n disjoint sets T 1, T2, T3, .........Tn where T1,
T2, T3, .........Tn are called sub trees.
Example
Terminologies:
Node: Node of a tree stores the actual data and links to the other node.
Root node: A first node written at the top is root node. The root node does not have the
parent.
Child: The node obtained from the parent node is called child node.
Predecessor: Every node N in a tree except root has a unique parent called as predecessor of
N. Here B is the predecessor of D, E, H, I and J.
Successor: Every node N in a tree except the leaf nodes has a unique child called as
successor of N. Here D, E, H, I and J are the successor of B.
Siblings: Two or more nodes having the same parent are called siblings. Here D and E are
siblings since they have same parent B.
Ancestors: The node n1 is said to be an ancestor of other node n2 if n1 is either the father of
n2 or the father of some ancestor of n2. Here A is the ancestor of B, D, E, H, I.
Descendant: The node n1 is called the descendant of node n2, if the node n2 is reachable
from n1. Here H is the descendant of D, B, A.
Degree: The number of sub trees of a node is called its degree. Here the node B has two sub
trees. So, degree of node B is 2.
Level: The distance of a node from the root is called level of the node. (or) Level is the rank
of hierarchy. The level of root node is 0.Here the level of D is 2.
Height (Depth): The height of the tree is defined as the maximum level + 1 of any leaf in the
tree. Here height of D is 3
Forest: A forest is a set of disjoint trees. The representation of forest is similar to tree.
Example in the above figure if we remove the root of tree a forest is created with 2 trees
headed by node B and C as root.
Binary Tree:
i)T is empty or
iii) the remaining nodes of T form only upto two disjoint binary trees T1 and T2 which are
called the left sub-tree and right sub-tree.
Strictly binary tree is a binary tree that has non-empty left and right sub trees. The out degree
of every node is either zero or 2.
A complete binary tree is a binary tree, which is completely filled, with the possible
exception of the bottom level, which is filled from left to right.
ii)For any node in the tree with a right descendant at level n, the node must have a left child
and every left descendant of node is either a leaf at level n or has two children.
A binary tree data structure is represented using two methods. They are:
1. Array Representation
2. Linked List Representation
To represent a binary tree of depth 'n' using array representation, we need one dimensional
array with a maximum size of 2n + 1.
Advantages
1. It is suitable for complete binary tree
2. Efficient if the tree does not go for changes such as insertion and deletion
Disadvantages
1. Not suitable for normal binary trees
2. It uses static allocation so that leads to memory wastage.
Example:
Advantage
Disadvantage
1. Extra memory is required to maintain the left link and right link pointers
Traversal is a process of visiting each nod exactly once in a systematic order. Binary tree has
three types of traversals.
1. Preorder
2. Inorder
3. Postorder
1. Preorder Traversal
The preorder traversal of a binary tree can be recursively defined as follows:
• Process the node data (D)
• Traverse the left subtree in preorder (L)
• Traverse the right subtree in preorder (R)
Algorithm:
Call pre_order(ptr->left)
Step 3: Traverse the right sub tree recursively in preorder
If ptr->right ≠ NULL
Call pre_order(ptr->right)
Step 4: return
Explanation:
Using the above algorithm we write the preorder traversal of the below binary tree.
2. Inorder Traversal
The inorder traversal of a binary tree can be recursively defined as follows:
• Traverse the left subtree in preorder (L)
• Process the node data (D)
• Traverse the right subtree in preorder (R)
Algorithm:
Print ptr->info
Step 4: Traverse the right sub tree recursively in inorder
If ptr->right ≠ NULL
Call in_order(ptr->right)
Step 5: return
Explanation:
Using the above algorithm we write the inorder traversal of the below binary tree.
Step 1: It visit the root node. It check left node is NULL or not. Here it has value 5
Step 2: It visit the node 5. It check left node is NULL or not. Here it has value 9
Step 3: It visit the node 9. It check left node is NULL or not. Here the left child is NULL.
Step 4: So it process the data.
Step 5:Recursively it call in_order() until all the node has been visited.
3. Postorder Traversal
The postorder traversal of a binary tree can be recursively defined as follows:
• Traverse the left subtree in preorder (L)
• Traverse the right subtree in preorder (R)
• Process the node data (D)
Algorithm:
Call post_order(ptr->right)
Step 4: Process the root node.
Print ptr->info
Step 5: return
Explanation:
Using the above algorithm we write the postorder traversal of the below binary tree.
Step 1: It visit the root node. It check left node is NULL or not. Here it has value 5
Step 2: It visit the node 5. It check left node is NULL or not. Here it has value 9
Step 3: It visit the node 9. It check left node is NULL or not. Here the left child is NULL.
Step 4: So it process the data.
Step 5:Recursively it call post_order() until all the node has been visited.
Explanation
Using the above create procedure we construct a binary search tree. Let the data are
56, 38, 10, 65, 72, 44 and 50
Step 1: Create the root node
5
6
Step 2: Take the second element 38, which is less than 56. So create a left child.
Step 3: Take the third element 10, which is less than 56. So go to left of 56. 10<38, so create
a left child.
Step 4: Likewise it compares value and node and add the node in corresponding order.
3 6
1 4 7
5
Tree Search
Searching an item in a binary search tree is finding the element in the tree. It is faster than
searching in binary trees, arrays or linked list.
• An AVL tree is a binary tree in which the heights of the left sub tree and height of the
right sub trees of the root differ by at most 1 and in which the left and right subtrees
are again AVL trees.
• The structure of an AVL tree is same as binary search tree additionally it balances the
height using balance factor
• Search
• Insert
• Delete
AVL Rotation
Rotation is the process of moving nodes either to left or to right to make the tree balanced.
There are four types of rotations depending upon where the new node is inserted.
Left to Left rotation: When the pivot node is left heavy and the new node is inserted in left
sub tree of the left child of pivot node then the rotation performed is left to left rotation
Right to Right rotation: When the pivot node is right heavy and the new node is inserted
in right sub tree of the right child of pivot node then the rotation performed is right to right
rotation
Left to Right rotation: When the pivot node is left heavy and the new node is inserted in
right sub tree of the left child of pivot node then the rotation performed is left to right rotation
Right to Left rotation: When the pivot node is right heavy and the new node is inserted in
left sub tree of the right child of pivot node then the rotation performed is right to left rotation
• Step 1 - Insert the new element into the tree using Binary Search Tree insertion logic.
• Step 2 - After insertion, check the Balance Factor of every node.
• Step 3 - If the Balance Factor of every node is 0 or 1 or -1 then go for next operation.
• Step 4 - If the Balance Factor of any node is other than 0 or 1 or -1 then that tree is
said to be imbalanced. In this case, perform suitable Rotation to make it balanced and
go for next operation.
Consider an AVL tree by inserting the following elements in the given order
63, 9, 19, 27, 18, 108, 99, 81
Example
Construct a max heap tree with the given data values: 25, 35, 20, 10, 45, 70, 50
The following steps are involved deleting a node from the heap tree
Heap Sort
Heap sort is one of the sorting algorithms used to arrange a list of elements in order.
Example
Trie: Definition
• Trie is an ordered tree data structure that is used to store a dynamic set or associative
array where the keys are usually strings.
• It is a tree of order m either empty or consisting of an ordered sequence of exactly m
tries each of order m.
Trie is a special data structure used to store strings that can be visualized like a graph. It consists
of nodes and edges.
• Each node consists of maximum 26 childrens and edges from parent to children
• 26 pointers are 26 English alphabets.
• Strings are stored in top to bottom fashion.
• All prefixes of length 1 stored at until level 1
• All prefixes of length 2 stored at until level 2 and so on.
Example
Advantages of Tries
• Faster Search
• Less space
• Longest Prefix matching
Disadvantages of Trie
• Some cases trie is slower than hash table while searching data.
Applications of Trie
• To store a Dictionary
• Spell-checking software
The process of searching for data from external storage (outside memory) is known as
external searching or external memory searching. Example: B-Tree
B-Tree
• A B-Tree is a self-balancing m-way tree data structure that allows searches, accesses,
insertions and deletions in logarithmic time.
• Each node in a B-Tree of order m can have at most m children and m-1 keys
B-Tree Properties
• Every node in the B tree has at most m children and m-1 keys
• Every node in the B tree except the root and leaf nodes has atleast m/2 children
• The root node has at least two children if it is not a leaf node.
• All leaf nodes are at the same level
B-Tree Operations
• Searching
• Insertion
• Deletion
• Step 1: Search the B-Tree to find the leaf node where the new value or key is to be
inserted.
• Step 2: If the leaf node is full, (it already contains (m-1) keys)
1. Insert the new key into the existing set of keys in order
2. Split the node into two halves
3. Push the middle element upward to its parent node. If the
parent node is full, then split the parent node using the step 2
procedure.
• Step 3: If the leaf node is not full, then insert the new key into the node, keeping the
elements in the order.
2. If the node has a minimum number of keys, then first we will check the number of
keys in the adjacent leaf node.
a. If the number of keys in the adjacent node is more than the minimum number
of keys, then the first key of the adjacent leaf node will go to the parent node,
and the key parent in the parent node will be combined together in a single
node.
b. If the parent node has less than the minimum number of keys then the same
steps will be repeated until we get a minimum number of keys
• The key from the node is deleted, and its place will be occupied by either its successor
or predecessor key
• If both predecessor and successor nodes have keys less than the minimum number
then the keys of the successor and predecessor are combined
Consider the B tree of order 3 given below and perform the following operation a) insert
122, 88 and b) delete 37, 110
Application of B-Trees
Applications of trees
I qnyh.
qsarA q h -l
1.otur ) and a ao.t F o5
:+' ) b"la
atuyt
4=(v,tt
+u'fu,a
y=\ A,a,(,D J
E - \ h 'r,'
( ( h't )
'(B 'c) '(c 'D)
j D
?.-Diwh.t qne,Fh,
stba^df
fl'^f
ca[b"l s,L
r" (v 1
tt "[
f.Y
q E ) t'th k"t
y)cr
fftu
B,nd €t!€
1Lt )
ta) suLo1ta,ph
l
, ,ojou,', ad -1
"tub"t ,"atkur
, .' -l vorh,
ru/1 t^t rclt h t i ,11
i,-And,u t i .>
a*Jq,, t) ,
r]trF.{r[,iu!I))= r
lnc|a", a*zb/.,u3). 3
- "u re,
1nc{.?
ap
(,). 2 ul c!|1,or t n) = a
1 'DcX
*o (t). h
,*a (:l :
[*) ' z
"i
fl,"!,h ;t trr
ffi, lalflorL drl tt"
"t.t j 'f
Lo tlat
T"fh
r& h
Plrt,
I
h sinyb C,t i! .sa; d Lr ha t''Pbtt i7
nw7'1,
wr&>r q ts
I 1
I
fl
Pl k" t
3
kr [n t-!
4
ShonaL c"\,hs
hn "nclr*tctad
L ca llt rl ct'D ckd ial
?
0(!t"J ftu, cl \athta, ff,oa rtrt-
1or
1kr'
L
)
-t
.3 p)
o
to) tomtttad ctrxa7h Ir] ,51,onfu tearrc c h'l pr
x*
ta NLi
n fl'"Ph
h contishEowLv$
wo i,,1
Jal: E oi
, ,r
rx,, and LLbiflhb 6w ',rlt.n,"l
lo cr,o' Or1
1"
v
4 ( 5
t9
?
tr . PoFl, ,
Pok^ b
Vo l. Vl1 q ra.,!th
srL,tr nu a ""tf
hT
:[-::i,. vo and ot c!;.3
\vo,a ,u ,u,ur, vn-, , o6,v" ]
2
fl
,"p1, *ttt "" ,,1'1"
LI t,
tl. L
A,) ,+ I t) t
h wh;6 sta,Ls ,,.,,c1 an{'
nl +fu J4h.! !'elt.). i5
n""r
!;a"" ,lah s,l,u,t.e.
b,. btnraon LL'diJ\ l;. r,t7atent 4 1/LarL.
t.hd1acer,cttr
A h.tjacc ^.,1 l,s t
,l na-ti t :
^di
-]I'c d*a.rrtL,l nv-h,ix , t o, nak,x wi.
u:fun T]"re
a- d t j)
o.ltr -tfu
r
1,*
d
fl'"rh
&u t6,l X
L utn
Fo, u.,d;r*c l,d q
fl fA
i.(;,l) 6E o, (j i\€ E
ndt"i x = A(i,i)=
4 1
o a&,Y ui+e t
trot a Jiutt d q
T16
llti,.l)eE)
hd.1au nt1 matvix , A( | ,i) .\
to uLored
hfr Q (,,,rr
x
fr.t
t1
j hh l-
ncLH bl',"J
:l
d4ii.ili, n .
w(,.,j) I( ,j) c€
h(i,i J -
hcljout c;1 n atr,'c =
I & Atl*t oigz
+
Llnd,,r,. Ld Di.&,hd t
A.tj"uh.l hatu t x
4 1
h
I o lo I alo
2 I ol z
3 I o
3 oooo
lf r0 ooio
[lar h larl
nllyun1 fi, ,,
') 3 +
I
L ,
3 3
l
z hdt
?n
", ^:'J Ltt r,e ptatt"taho" #, arth vc,hr in
.
tLt
?^l)'
Ael ctcab,l lt; atorc- all
)< 1t,,
1 1 l''^hr
Gnlad Ls[ c,r"os ,J +hr adAarq.,l
'f
t" eat l, ,c,hx i" 1A" f,
*t1 t,1 F
4 h1
aa1 tt [@
afitu) 5
^ct1l51
U*,clil,ttnl Gnnrl"
4t,1
3
a,t; h1
agkl I
aditLl
rl E,[@
4hr
UNIT 3 Data Structures Using C 31
A vertex in an undirected connected graph is an articulation point (or cut vertex) if removing
it (and edges through it) disconnects the graph.
Biconnected graph
1) It is connected, i.e. it is possible to reach every vertex from every other vertex, by a
simple path.
2) 2) Even after removing any vertex the graph remains connected. (No articulation points
in the graph
Graph Traversal
Graph traversal is a technique used for a searching vertex in a graph. That means using graph
traversal we visit all the vertices of the graph.
There are two graph traversal techniques and they are as follows...
Algorithm
Breadth First Search is a traversal technique in which we traverse all the nodes of the graph in
a breadth-wise motion. In BFS, we traverse one level at a time and then jump to the next level.
The BFS algorithm makes use of the queue data structure for implementation.
Procedure
Algorithm
Topological sorting
Topological sorting for Directed Acyclic Graph (DAG) is a linear ordering of vertices such
that for every directed edge u v, vertex u comes before v in the ordering. Topological
Sorting for a graph is not possible if the graph is not a DAG.
Example
Algorithm
SORTING
Sorting is a procedure to arrange data in a specified order either ascending or descending.
Types of sorting
There are many methods of sorting. Some of them are
1) Bubble sort
2) Insertion sort
3) Selection sort
4) Merge sort
5) Quick sort
6) Shell sort
Efficiency Parameters
The sorting method that is to be implemented depends on how it behaves in each situation.
Some of the parameters are:
a) Execution time
It is the time required for the execution of the program. This time required is more if
there are more number of comparisons and exchange of data.
b) Space or memory
It is the amount of space required to store data. The more data to be sorted, the
memory required is more.
c) Coding time
It is the time required to develop a sorting technique for the given problem. Efficiency
of any sorting technique can be represented using mathematical notations. All the
sorting technique efficiency are in the range of O(nlogn) to O(n2)
It is the function which gives the running time of the algorithm in terms of size of the input
data ‘n’. There are three cases for finding the complexity f(n)
i) Worst Case – In this, maximum number of comparisons are made.
ii) Average Case – In this, average number of comparisons are made.
iii) Best Case – In this, minimum number of comparisons are made.
BUBBLE SORT
This is one of the simplest method of sorting. In this method, to arrange a list of numbers in
ascending order, it follows the procedure as below
If the first element > second element, the position of the elements is exchanged. The second
element is compared with the third and the process continues until all the elements of the
array are compared. This process is referred to as 1stpass.Therefore at the end of first pass,
the largest element bubbles down to the last position.
In the second pass, the same procedure is followed leaving out the last element since it is
already in position. This pass brings the second largest.
This procedure is repeated until there are no elements for comparison.
Eg:
Algorithm
BUBBLESORT(A[n])
A is an array of n elements to be sorted
Step 1: for pass = 1 to n – 1
Step 2: for j= 0 to n – pass - 1
Step 3: if a[j] > a[j+1] then
temp = a[j]
a[j] = a[j]+1
a[j]+1 = temp
Step 4: End for
Step 5: End for
Function to Sort n elements using bubble sort
void bubble_sort(int a[], int n)
{
int pass, temp, j;
for(pass=1; pass<n; pass++)
{
for(j=0; j<n-pass-1; j++)
{
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
}
SELECTION SORT
The selection sort is the selection of an element and placing it in proper position. In selection
sort, first we will search the smallest element in an array and interchange with the first
element. Then search the second smallest element and interchange with the second element
and continue this process until all the elements are completed.
Consider the array A[5] with unsorted elements and sort them by applying selection sort
temp= a[k];
a[k]= a[loc];
a[loc]= temp;
}
printf("\n The sorted array is : \n");
for(i=0; i<n; i++)
{
printf("%d ", a[i]);
}
getch();
}
Insertion Sort
The insertion sort inserts each element in appropriate position.
The first element of the array is assumed to be in correct position. The next element is
considered as a key element and compared the sorted elements ie, the elements before the key
element and inserted in its proper position. This procedure continues until all the elements are
inserted in their correct positions.
Algorithm
INSERTION SORT(A[],n)
Step 1: Repeat step 2 to step 5 for pass = 1 to n-1
Step 2: Set K = A[pass]
Step 3: Repeat Step 4 for j = pass -1 to 0
Step 4: if( K < A[j])
A[j+1] = A[j]
Step 5: A[j+1] = A[j]
Step 6: Exit
Shell Sort
It is based on insertion sort algorithm. It compares elements that are distant apart rather
than adjacent element. The spacing between elements is known as Gap or Interval. In every
pass, Gap is reduced by 1 till we reach last pass when gap is 1.
Algorithm
shell_sort(a,n)
{
while (incr > 1)
{
for(j=incr; j<n; j++)
{
k=a[j];
for(i= j - incr; i > 0 && k < a[i]; i = i-incr)
a[i + incr] = a[i];
a[i + incr] = k;
}
incr = incr - 2;
}
}
Example
Consider the following elements in unsorted order and sort them by applying shell sort
Here, in the first pass, the element at the 0th position will be compared with the element at
5th position. If the 0th element is greater, it will be swapped with the element at 5th position.
Otherwise, it remains the same. This process will continue for the remaining elements.
Complexity of Shell sort
Best Case: O(n*logn)
Average Case: O(n*log(n)2)
Worst Case: O(n2)
Hashing
Definition
Hashing is the process of mapping keys to their appropriate locations in hash table. Hashing
in data structure is a two-way process
1. The hash function converts the item into a small integer or hash value
2. This hash value is used to store the data in a hash table.
Hash Table
Hash table is a data structure which stores data in an associative manner.
Hash function
The function of converting the key into table or array index is called hash function. It is
denoted by H.
Or
A hash function is a mathematical formula which when applied to a key that produces an
integer which can be used as an index for the key in the hash table.
Whenever there is more than one key that point to the same slot in the hash table, this
phenomenon is called collision.
For example, let keys be 11, 12, 23, 42, 51 and let the hash function be h(k) =k mod 10
h(16)=16 mod 10 = 6
h(12)= 12 mod 10 = 2
h(23)= 23 mod 10 = 3
h(42)= 42 mod 10 = 2
h(51)= 51 mod 10 = 1
Thus, both the keys 12 and 42 are generating the same index. So which value will we store in
that particular index as we can store only one of them.
Types of hash Function
1. Division method
2. Mid square method
3. Folding method
4. Mixed method
Division Method
This method divides x by M and then it uses remainder as the index of the key in hash table.
ℎ(𝑥 ) = 𝑥 𝑚𝑜𝑑 𝑀
Example
H(1675)= 1675 mod 97 =1675 % 97 = 26
H(2432)= 2432 mod 97 = 2432 % 97 = 07
H(5209)= 5209 mod 97 = 5209 % 97 = 68
Mid Square Method
In this method, we square the key first, then we take some digits from the middle of this number
as the generating address.
Example
K 1675 2432 5209
2
K 2805625 5914624 27133681
H(K) 56 46 36
The third and fourth digits, counting from the right are chosen for the generating hash address.
Folding Method
The key is broken into pieces and then adding all of them to get the hash address. Each piece
should have the same number of digits except the last piece.
𝐻(𝐾 ) = 𝐾1 + 𝐾2 + ⋯ + 𝐾𝑛
Example
H(1675) = 16 + 75 = 91
H(2432) = 24 + 32 = 56
H(5209) = 52 + 09 = 61
H(8677)= 86 + 77 = 163 = 63
Mixed Method
If we use more than one type of hash function for generating address in the hash table, then it
is called as Mixed method.
Consider the following example with 8 digit key 27862123
i) Folding method: H (27862123) = 27 + 8621 + 23 = 8671
ii) Division method: H ( 8671 ) = 8671 % 97 = 38
Collision Resolution
A method used to solve the problem of collision is called collision resolution technique. The
techniques are:
1. Open Addressing
2. Chaining
1. Open Addressing
The process of examining memory locations in the hash table is called probing. Open
addressing computes new position using a probe sequence and the next record is stored in that
position. Open addressing can be implemented using
i. Linear probing
ii. Quadratic probing
iii. Double probing
iv. Rehashing
i. Linear probing
This hashing technique find the hash key through hash function and maps the key on
particular position in the hash table. In case if the key has same hash address, then it
will find the next empty position in the hash table.
Example
Consider a hash table with some elements.
25, 46, 10, 36, 18, 29 and 43 and the “table size” is 11
Here, 25 will be inserted at the 3rd position in the array. Next 46 will be inserted at 2 nd
position and 10 will be inserted at 10th position. Now 36 has same hash address 3 that
is already by 25. So it will be inserted in the next free place which is 4th position.
Similarly, 18 and 29 also has the same hash address 7. So 18 will be inserted at 7th
position and 29 will be inserted at 8th position which is free. Now again 43 has the same
hash address 10 that is already occupied by 10. So 43 will be inserted at the next free
place which is 0th position.
Disadvantage:
• Records tend to cluster I.e., if half the table is full then it is difficult to find free
space
ii. Quadratic probing
In quadratic probing, the location of insertion and searching takes place in (a+i2) where
i=0,1,2,…. that is, at the location of a, a+1, a+4, a+9….. So it will decrease cluster
problem. If the table size is prime number, then it will not search half of the hash table
positions.
2. Chaining
Collision resolution by chaining combines linked representation with hash table. When
two or more records hash to the same location, these records are constituted into a
singly-linked list called a chain. In chaining, we store all the values with the same index
with the help of a linked list
Example