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

All - Units - Data Structures

The document defines and describes various data structures including primitive and non-primitive data structures. It discusses linear data structures like arrays, linked lists, stacks, and queues as well as non-linear structures like trees and graphs. Key operations on data structures are also summarized such as insertion, deletion, traversal, searching, sorting, and merging. Mathematical notations and functions used in analyzing algorithms and data structures are also briefly explained.

Uploaded by

vishwa.tdm
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

All - Units - Data Structures

The document defines and describes various data structures including primitive and non-primitive data structures. It discusses linear data structures like arrays, linked lists, stacks, and queues as well as non-linear structures like trees and graphs. Key operations on data structures are also summarized such as insertion, deletion, traversal, searching, sorting, and merging. Mathematical notations and functions used in analyzing algorithms and data structures are also briefly explained.

Uploaded by

vishwa.tdm
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 124

UNIT 1 Data Structures Using C 1

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

Primitive Data Non-Primitive Data


Structure Structure

Linear Data Non-linear Data


int Structure Structure

char Array Trees

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

A[0] A[1] A[2] A[3]


Array may be 1D, 2D and Multi-dimensional.
Linked List: A list is a linear data structure, it is a collection of data items named as nodes
each node is divided into two fields that is data and link field. Example

SINDHI COLLEGE BANGALORE - 24


UNIT 1 Data Structures Using C 2

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

SINDHI COLLEGE BANGALORE - 24


UNIT 1 Data Structures Using C 3

Here, A is root node, C,D,E is leaf node, B is a internal node.


Graph: Graph is a finite set of ordered pair G=(V,E) where V is the vertices and E is the edges.
It is a collection of adjacent vertices.

B C

Operations on Data Structures:


The data structure can be classified as
• Insertion
• Deletion
• Traverse
• Searching
• Sorting
• Merging
Insertion: Adding a new element to the existing data structure.
Deletion: Deleting an element from Data Structure.
Traverse: Accessing each element exactly once.
Searching: Search a particular element in the list of elements present in the Data Structure.
Sorting: Arranging the elements in ascending or descending order.
Merging: Combining two sorted Data Structure into a single sorted Data Structure.

Algorithm: An algorithm is a step by step procedure to perform a specific task in a finite


amount of time.

Algorithm complexity: It is a measure of amount of time and space required by an algorithm


for an input of a given size ‘N’.
Time Complexity: Time complexity describes the amount of time an algorithm takes in terms
of the amount of input to the algorithm.
Space Complexity: Space complexity describes the amount of memory space an algorithm
takes in terms of the amount of input to the algorithm.

Mathematical notations and functions


1. Floor & Ciel function
Floor function provides the greatest integer that is not greater than the given value. The
symbol for floor function is ⌊ ⌋
Example x=4.678
⌊𝒙⌋ =4

SINDHI COLLEGE BANGALORE - 24


UNIT 1 Data Structures Using C 4

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

SINDHI COLLEGE BANGALORE - 24


UNIT 1 Data Structures Using C 5

It is a collection of elements or data items of homogenous type.


Linear Array
It is a list of fixed size number N of similar datatype element (or) data item
The elements in linear array are stored sequentially in memory. Here n is the size of the
array. To find the length of the array
length of the array =UB – LB + 1
where LB is the lower bound, UB is the upper bound
Ex: int a[10]
Length of array=10-0+1
=11
It holds 11 elements
Array ADT
An array is a fixed collection of elements of same type. The array data such as size, type, the
index. The operation such as traverse, search, insert, delete, sort, merge.
Classification of Array:
It can be classified into
1. One Dimensional Array (1D)
2. Two-Dimensional Array (2D)
3. Multi-Dimensional Array (m-D)
One Dimensional Array
An array which has only one subscript is called one-Dimensional array.
General syntax: 𝑑𝑎𝑡𝑎𝑡𝑦𝑝𝑒 𝑎𝑟𝑟𝑎𝑦_𝑛𝑎𝑚𝑒 [𝑠𝑖𝑧𝑒];
Ex: int a[10];
Here a is the name of the array, int is the datatype and size is 10
Two-Dimensional Array
An array which has two subscripts is called two-Dimensional array.
General syntax: 𝑑𝑎𝑡𝑎𝑡𝑦𝑝𝑒 𝑎𝑟𝑟𝑎𝑦_𝑛𝑎𝑚𝑒 [𝑟𝑜𝑤_𝑠𝑖𝑧𝑒][𝑐𝑜𝑙_𝑠𝑖𝑧𝑒];
Ex: int mat[2][2];
Here mat is the name of the array, int is the datatype and row_size is 2, col_size is 2. It can
hold 4 elements.
Multi-Dimensional Array
An array which has more subscripts is called multi-Dimensional array.
General syntax: 𝑑𝑎𝑡𝑎𝑡𝑦𝑝𝑒 𝑎𝑟𝑟𝑎𝑦_𝑛𝑎𝑚𝑒 [𝑠𝑖𝑧𝑒1][𝑠𝑖𝑧𝑒2]… . … .[𝑠𝑖𝑧𝑒_𝑛];

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

SINDHI COLLEGE BANGALORE - 24


UNIT 1 Data Structures Using C 6

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
{

SINDHI COLLEGE BANGALORE - 24


UNIT 1 Data Structures Using C 7

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

SINDHI COLLEGE BANGALORE - 24


UNIT 1 Data Structures Using C 8

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

SINDHI COLLEGE BANGALORE - 24


UNIT 1 Data Structures Using C 9

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

SINDHI COLLEGE BANGALORE - 24


UNIT 1 Data Structures Using C 10

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

SINDHI COLLEGE BANGALORE - 24


UNIT 1 Data Structures Using C 11

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

SINDHI COLLEGE BANGALORE - 24


UNIT 1 Data Structures Using C 12

Let f(n) = 2n+3


lets take 2n+3 <=10n
let n=1
therefore 5<=10 is true for all n, n>=1
Here f(n) <=cg(n) for all n>=n0 where n0 = 1, c = 10, g(n) = n
Therefore, f(n) =O(n) which is closer to the function.

Omega (Ω) Notation


• This method is used to find the lower bound of an algorithm’s running time.
• It is the best case time complexity of an algorithm.
Definition: The function f(n)= Ω (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 omega Notation

Let f(n) = 2n+3


lets take 2n+3 >=1 * n
let n=1
therefore 5>=1 is true for all n, n>=1
Here f(n) >=cg(n) for all n>n0 where n0 = 1, c = 1, g(n) = n
Therefore, f(n) = Ω (n) which is closer to the function.

SINDHI COLLEGE BANGALORE - 24


UNIT 1 Data Structures Using C 13

Theta (θ) Notation


The theta notation can be used when the function f(n) can be bounded both from lower bound
and upper bound.
Definition: The function f(n)= θ(g(n)), if and only if there exists a positive constants c1,c2
and n0 such that c1*g(n)<=f(n)<=c2*g(n)
The following figure represents theta Notation

Let the function be F(n)=2n+3


1*n <= 2n+3 <= 10*n
This is in the form c1*g(n)<=f(n)<=c2*g(n)
Therefore, we can write F(n)= θ (n) and this is the average bound of a function f(n).

Row major and column major representation of multidimensional array


In Row Major Order, elements of a multi-dimensional array are arranged sequentially row
by row, which means filling all the index of first row and then moving on to the next row.
Example {1,2,3,4,5,6,7,8}

In Column Major Order, elements of a multidimensional array are arranged sequentially


column-wise which means filling all the index of the first column and then move to the next
column. Example {1,2,3,4,5,6,7,8}

SINDHI COLLEGE BANGALORE - 24


UNIT 2 Data Structures Using C 1

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

• Efficient memory utilization


• Insertion and Deletion operation are easier
• Dynamic Data Structure
• Extensive manipulation
• Arbitrary memory location
• Efficient memory utilization
Memory can be allocated when ever we are inserting a new node and we deallocate when it is
deleted.
• Insertion and Deletion operation are easier
Linked List flexibility in inserting a data item at a specified position and Deletion of a data
item from a given position.

• Dynamic Data Structure


Linked List can grow or shrink during the execution of program.
• Extensive manipulation
We perform a complex manipulation a Linked Link without having any prior knowledge of
memory space available.

• Arbitrary memory location


In Linked List memory location are not consecutive, it may arbitrary. But the data is linked
with previous node. So, we can store the data in affecting memory effectively by using the link
value in Linked List.
Disadvantages of Linked List
1. It requires more memory than array because each node has a pointer, which requires
more memory.

SINDHI COLLEGE BANGALORE - 24


UNIT 2 Data Structures Using C 2

2. Difficult to traverse the nodes in a linked list.


3. Reverse traversing in a linked list is very difficult, because it requires more memory for
the pointer.
Representation of Linked list in memory
List can be represented in 2 ways.
• Static representation
• Dynamic representation
Static Representation
Static representation of singly linked list maintains 2 arrays
1) INFO[] 2) LINK[]
Example
START
INFO[] LINK[]
1 A 3
2
3 B 5
4
5 C NULL
Here, INFO[1]=A, LINK[1]=3 ,
INFO[3]=B, LINK[3]=5 and
INFO[5]=C, LINK[5]=NULL.
i) The memory size of those 2 arrays should be sufficient to store the entire linked list
ii) Two arrays should be in equal size and parallel to each other.
Dynamic Representation
The process of allocating memory at runtime is known as dynamic memory allocation.
Functions for allocating memory:
i) malloc() ii) calloc()
Functions for deallocating memory:
i) free()
In dynamic representation of Linked List, a node is created dynamically whenever it required.
To create a node of Linked List, a structure is to be defined and it holds the data and address
of the next structure data.

SINDHI COLLEGE BANGALORE - 24


UNIT 2 Data Structures Using C 3

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:

• Singly Linked List


• Circular Linked List
• Doubly Linked List
• Header Linked List
• Circular Doubly Linked List
Singly Linked List
A singly linked list is a linear collection of data elements called nodes, where each node is
divided into 2 fields: Info field and link field. The link field points the next node and the link
field of last node points NULL.
Example:
START
10 58 24 NULL

Operations on Singly Linked List


• Creation
• Traversal
• Length
• Insertion
• Deletion
• Searching
• Sorting
• Merging
• Reversing
Creation
This operation creates a linked list. The following algorithm creates the Linked List
Algorithm
1. Create a node and assign the address to start pointer
CURNODE=(NODE*) malloc(sizeof(NODE));
START=CURNODE
2. Store the data
CURNODE→INFO=item;

SINDHI COLLEGE BANGALORE - 24


UNIT 2 Data Structures Using C 4

3. Store null character in link field


CURNODE→LINK=NULL
4. Return
Explanation
The first step is to create a node with 2 fields and assign the address of the node to start
START

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

The first step is to check START is NULL. Here START=2002

SINDHI COLLEGE BANGALORE - 24


UNIT 2 Data Structures Using C 5

The second step is to assign START value to CURPTR=START ie., CURPTR=2002


The third step it checks CURPTR is NULL, if it is not then it print the INFO value 10.
Repeatedly until CURPTR become NULL.
The following code illustrates the Linked List traversal
void display()
{
struct node *ptr;
if(start==NULL)
{
printf("\nList is empty\n");
return;
}
else
{
ptr=start;
printf("\nThe List elements are:");
while(ptr!=NULL)
{
printf("%dt",ptr->info );
ptr=ptr->next ;
}
}
}

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

SINDHI COLLEGE BANGALORE - 24


UNIT 2 Data Structures Using C 6

START
2010 2010 215 1003
10 90 24 NULL

The first step creates a node with two fields

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 fourth step to assign START as NEWNODE.


START
2025 2025 2010 215 1003
50 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

SINDHI COLLEGE BANGALORE - 24


UNIT 2 Data Structures Using C 7

{
temp->next=start;
start=temp;
}
}

2) Insert at the end of a Linked List


The following algorithm insert a node at the end of Linked List
Algorithm:
1. Is List is empty?
if(Start = = NULL)
Call insert at the beginning
Exit()
2. Assign the Start to CURPTR
CURPTR=Start
3. Traverse the List to obtain Last node address
while(CURPTR → LINK != NULL)
CURPTR=CURPTR → LINK
4. Create a node using malloc
NEWNODE=(NODE*) malloc(sizeof (NODE))
5. Store the data
NEWNODE→INFO=ITEM
6. Create a link between Last Node and NEWNODE
CURPTR → LINK = NEWNODE
NEWNODE→LINK=NULL
7. Exit
Explanation
Consider the following linked list contain 3 nodes
START
2010 2010 215 1003
10 90 24 NULL

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

In fourth step creates a node with two fields

2025

NEWNODE=2025
The fifth step stores data in INFO field

SINDHI COLLEGE BANGALORE - 24


UNIT 2 Data Structures Using C 8

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

3) Insert at the specified position in Linked List


The following algorithm insert a node a specified position in Linked List
Algorithm
1. Assign Start to CURPTR
CURPTR=Start
2. Check position if( POS == 1)
Call insert at beginning
Exit()

SINDHI COLLEGE BANGALORE - 24


UNIT 2 Data Structures Using C 9

3. Set the CURPTR to specified position


for ( i=0; i<pos-2;i++ )
CURPTR=CURPTR → LINK
4. Create a new node using malloc()
NEWNODE=(NODE*) malloc(sizeof(NODE))
5. Store data into NEWNODE → INFO
NEWNODE → INFO = ITEM
6. Create the link between NEWNODE and CURPTR
NEWNODE → LINK =CURPTR → LINK
CURPTR → LINK = NEWNODE
7. Exit
Explanation
Consider the following linked list contain 3 nodes
START
2010 2010 215 1003
10 90 24 NULL

In first step it assign Start value to CURPTR.


The second step it check position value if it is one it call insert at beginning()
In third step it set CURPTR to specified position.
In fourth step it creates new node

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

SINDHI COLLEGE BANGALORE - 24


UNIT 2 Data Structures Using C 10

printf("\nOut of Memory Space\n");


return;
}
printf("\nEnter the position for the new node to be inserted:");
scanf("%d",&pos);
printf("\nEnter the data value of the node:");
scanf("%d",&temp->info) ;

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

SINDHI COLLEGE BANGALORE - 24


UNIT 2 Data Structures Using C 11

Start= CURPTR → LINK


4. Using free() delete CURPTR
free(CURPTR)
5. Exit
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 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);
}
}

2) Delete a node from end of a Linked List


This operation delete the node from end of Linked List
Algorithm
1. Is List is empty?
if( Start = = NULL)
print (“List is Empty”)
else
step 2
2. Check list contain one element

SINDHI COLLEGE BANGALORE - 24


UNIT 2 Data Structures Using C 12

if (Start → LINK = = NULL) then


Start = NULL
else
Step 4
3. delete start node
free (Start)
4. assign Start value to CURPTR
CURPTR = Start
5. assign NULL to PREPTR
PREPTR= NULL
6. Traverse the Linked List until the CURPTR pointer points the last node.
while(CURPTR → LINK != NULL)
{
PREPTR = CURPTR
CURPTR= CURPTR → LINK
}
7. Delete CURPTR
free (CURPTR)
8. Set PREPTR → LINK = NULL
9. Exit
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 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)

SINDHI COLLEGE BANGALORE - 24


UNIT 2 Data Structures Using C 13

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

3) Delete a node from a specified position in Linked List


This operation delete the node at a given position.
Algorithm
1. if (POS = = 1)
call delete_beginning()
else
goto step 2
2. set CURPTR to Start
CURPTR=Start
3. set PREVPTR to NULL
PREVPTR = NULL
4. set CURPTR to specified position using loop
for(i=1; i<POS; i++)
{
PREVPTR=CURPTR
CURPTR=CURPTR → LINK
}
5. create link between PREVPTR and the nextnode of CURPTR
PREVPTR → LINK = CURPTR → LINK
free(CURPTR)
6. Exit

SINDHI COLLEGE BANGALORE - 24


UNIT 2 Data Structures Using C 14

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.

In seventh step delete CURPTR


In eighth step set PREPTR → LINK as NULL
START
2002 2002 198
10 58 NULL

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 ;

SINDHI COLLEGE BANGALORE - 24


UNIT 2 Data Structures Using C 15

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

SINDHI COLLEGE BANGALORE - 24


UNIT 2 Data Structures Using C 16

It is a process of searching an element in a linked list.


Algorithm
1. Assign CURPTR= start, LOC = NULL
2. Repeat step 3 while (CURPTR != NULL)
3. If(ITEM = = CURPTR → INFO)
{
LOC= CURPTR
Print “Search Successful”
}
Else
CURPTR= CURPTR → LINK
4. If (LOC = = NULL)
Print “Search Unsuccessful”
5. Exit

Consider a Linked List with the following nodes and it search 58


START
2002 2002 2015 198
10 58 24 NULL

In the first step it assigns CURPTR= Start and LOC =NULL


In the second step it checks CURPTR is NULL if not it repeat step 3
In the third step it checks ITEM = = CURPTR → INFO if so assign CURPTR to LOC and
display “Successful” otherwise CURPTR = CURPTR → LINK
In the fourth step, if LOC is NULL then display “Unsuccessful”
In the fifth step exit

Circular Linked List


Circular linked list is similar as singly linked list except that the last node always points the
first node instead of null.
Consider the following pictorial representation shows circular linked list.

2002 2015 198


10 58 24

In circular linked list, only one pointer is used for insertion and deletion.
Circular linked list contains the following operations

SINDHI COLLEGE BANGALORE - 24


UNIT 2 Data Structures Using C 17

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

SINDHI COLLEGE BANGALORE - 24


UNIT 2 Data Structures Using C 18

}
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

SINDHI COLLEGE BANGALORE - 24


UNIT 2 Data Structures Using C 19

Advantages of circular linked list


1. It can be traversed from any node
2. All the nodes link address will have valid address instead NULL
3. Node can be inserted or deleted from any position of the linked list
4. Traverse the whole list from any node
Disadvantages of circular linked list
1. Difficult to reverse the circular linked list.
2. If proper care is not taken, then the problem of infinite loop can occur
Doubly Linked List
A doubly linked list is the kind of linked list, in which a node has three fields:

• 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:

BACK INFO FORW


The following code declare the doubly linked list using dynamic implementation.
struct node
{
int INFO;
struct node *BACK;
struct node *FORW;
};
The pictorial representation of doubly linked list is illustrated below.
START
1800 1800 4020 5042
NULL 24 4200 1800 67 5042 4020 80 NULL
The following program creates a node in doubly linked list and display its data.
#include<stdio.h>
#include<conio.h>
#include<ctype.h>
struct node
{
int INFO;
struct node *BACK;
struct node *FORW;
};
typedef struct node NODE;

SINDHI COLLEGE BANGALORE - 24


UNIT 2 Data Structures Using C 20

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

SINDHI COLLEGE BANGALORE - 24


UNIT 2 Data Structures Using C 21

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.

SINDHI COLLEGE BANGALORE - 24


UNIT 2 Data Structures Using C 22

• 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:

• Grounded header linked list


• Circular header linked list
Grounded header linked list
The grounded header linked list is also referred as singly header linked list. In this the last node
LINK field contains the NULL pointer.
Example
START
2002 2002 2015 198
58 24 NULL
Header node

Circular header linked list


A linked list in which last node points to the header node is called circular header linked list.
Example

Head Node 2015 198


58 24

SINDHI COLLEGE BANGALORE - 24


UNIT 2 Data Structures Using C 23

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

SINDHI COLLEGE BANGALORE - 24


UNIT 2 Data Structures Using C 24

1. Check stack overflow using TOP= = MAXSTK -1, here it is false


2. Increment TOP value by TOP=TOP+1

TOP
5
8
1

3. Insert item at the TOP using S[TOP]=item

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

SINDHI COLLEGE BANGALORE - 24


UNIT 2 Data Structures Using C 25

2. Delete the TOP item

TOP
8
1

3. Decrement TOP value by 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

1. Check stack is underflow or not, here TOP=2and MAXSTK=5. Therefore, go to step 2


2. Access the TOP of the element and print using Loop 5 8 1
3. Return
Application of stack
• Recursion
• Reversal of a string
• Checking the parenthesis matching

SINDHI COLLEGE BANGALORE - 24


UNIT 2 Data Structures Using C 26

• Postfix expression evaluation


• Infix to postfix conversion
• Infix to prefix conversion
RECURSION
It is a process of calling the function repeatedly itself. The repeated calling is terminated by a
specific condition.
Types
• Direct
• Indirect
Direct Recursion
This type calls itself repeatedly until certain condition is satisfied
Example
fact(int n)
{
if(n==0)
return 1;
else
return (n* fact(n-1));
}
Indirect Recursion
This type calls another function which eventually calls the same function repeatedly
Example
fun1 (int a)
{
fun2( b);
}
fun2 (int c)
{
fun1(x);
}

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

The factorial is defined as the product of all integers between n and 1.


The recursive description can be expressed as:

1 𝑖𝑓 𝑁 = 0
FACTORIAL(N) = { }
𝑁 ∗ 𝐹𝐴𝐶𝑇𝑂𝑅𝐼𝐴𝐿 (𝑁 − 1) 𝑖𝑓 𝑂𝑡ℎ𝑒𝑟𝑤𝑖𝑠𝑒

SINDHI COLLEGE BANGALORE - 24


UNIT 2 Data Structures Using C 27

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

Recursion : Example 2 - Fibonacci Series


Fibonacci series is a peculiar series of integers where each element in the series is the sum of
the two preceding elements. Eg: 0 1 1 2 3 5 8 13 21 ……………
The general Fibonacci series can be represented as

0 𝑖𝑓 𝑁 = 0 𝑜𝑟 𝑁 = 1
Fib(N)={ 1 𝑖𝑓 𝑁 = 2 }
𝑓𝑖𝑏(𝑁 − 1) + 𝑓𝑖𝑏(𝑁 − 2) 𝑖𝑓 𝑁 > 2

SINDHI COLLEGE BANGALORE - 24


UNIT 2 Data Structures Using C 28

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

The following represents the Fibonacci recursive call illustration.

Recursion : Example 3 - Tower of Hanoi Problem


Tower of Hanoi problem is a game where a disk is to be moved from one source pillar to a
destination pillar using a temporary pillar. To solve this problem, we have to follow three
conditions. They are:
• Only one disk can be moved at one time, from one pillar to another
• A larger disk cannot be placed on the smaller disk
• Only the top disc on any pillar may be moved to any other pillar

SINDHI COLLEGE BANGALORE - 24


UNIT 2 Data Structures Using C 29

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)

The solution is represented in the following figure:

Hence the sequence for n=3 is


S→D S→T D→T S→D T→S T→D S→D

Recursion : Example 4 - Greatest Common Divisor (GCD)


Greatest Common Divisor problem can be solved using recursion
The recursive description can be expressed as:

𝐺𝐶𝐷(𝑛, 𝑚), 𝑖𝑓 𝑛 > 𝑚


GCD(𝑚, 𝑛) = { 𝑚, 𝑖𝑓 𝑛 = 0 }
𝐺𝐶𝐷(𝑛, 𝑀𝑂𝐷(𝑚, 𝑛)), 𝑂𝑡ℎ𝑒𝑟𝑤𝑖𝑠𝑒

SINDHI COLLEGE BANGALORE - 24


UNIT 2 Data Structures Using C 30

The steps during this process can be represented as follows:

GCD(288, 108)= GCD(108,72)


GCD(108, 72)=GCD(72, 36)
GCD(72, 36)=GCD(36, 0)
GCD(36, 0)= 36
GCD(72, 36)= 36
GCD(108,72)= 36
GCD(288, 108)= 36
The following program find GCD of three numbers
#include<stdio.h>
int gcd(int m, int n)
{
if(n= = 0)
return m;
else if(n>m)
return (gcd(n,m));
else
return (gcd(n, m%n));
}
void main()
{
int k, m, n;
printf("Enter the three numbers: ");
scanf("%d %d %d", &k, &m, &n);
printf("GCD (%d, %d, %d) = %d ", k, m, n, gcd(k, gcd(m, n)));
}
Output
Enter the three numbers: 4 6 8
GCD (4, 6, 8 ) = 2

Checking the Parenthesis Matching


Stacks are most useful for checking the parenthesis matching in an expression.
Algorithm:
Step1: Scan the symbols of expression from left to right
Step2: If the symbol is a left parenthesis then push it on the stack
Step3: If the symbol is right parenthesis
if the stack is empty
valid = false
else
pop an element from the stack
if the popped parenthesis does not match the parenthesis being scanned
valid= false
Step4: After scanning all the symbol if stack is not empty then
valid = false

SINDHI COLLEGE BANGALORE - 24


UNIT 2 Data Structures Using C 31

Show that the expression ((1+2)*3) is valid


Scanned Symbol ((1+2)*3) Stack Operation Performed

Push()
( (
Push()
( ( (

1 ( (

+ ( (

2 ( (
Pop()
) (

* (

3 (
Pop()
)

Polish Notation of Arithmetic Expressions


The great Polish Mathematician Jan Lukasiewich introduced a new technique for the
representation of arithmetic expressions. According to him arithmetic expressions are
classified into three categories.
• Infix notation
• Postfix notation
• Prefix Notation
Infix Notation
Operator is placed in between the operands eg: a + b
Prefix Notation (Polish Notation)
Operator is placed before operands eg : +ab
Postfix Notation (Revers polish notation) or Suffix notation
Operator is placed after operands eg: ab+
To parse any arithmetic expression, we need to take care of
• operator precedence
• associativity

SINDHI COLLEGE BANGALORE - 24


UNIT 2 Data Structures Using C 32

Conversion from infix to postfix expression


Algorithm
1. Push ‘(‘ on the stack and add ‘)’ at the end of the infix expression Q.
2. Read all the symbols one by one from left to right in the given Infix Expression.
3. If the scanned symbol is operand, then print it (Output).
4. If the scanned symbol is left parenthesis '(', then Push it on to the Stack.
5. If the scanned symbol is operator ⊗ then
1. Repeatedly pop the operators from stack and print it which has the same
precedence or higher precedence than operator ⊗
2. PUSH ⊗ to STACK
6. If the scanned symbol is right parenthesis ')’, then
1. Repeatedly Pop all the contents of stack and print each poped symbol to the
result.
2. Remove the left parenthesis’ (‘
7. Exit

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

SINDHI COLLEGE BANGALORE - 24


UNIT 2 Data Structures Using C 33

Evaluation of Postfix expression


Algorithm
Step 1: Add “#” at the end of P
Step 2: Repeat scanning P from left to right and repeat step 3 and 4 for each element of P
until “#” is encountered.
Step 3: If an operand is encountered, push it onto STACK
Step 4: If an operator ⊗ is encountered:
1. Remove the two top elements of STACK. If A is the top element, B is the next
top element.
2. Evaluate B⊗ A
3. Push the result of (2) of step 4 back onto STACK
Step 5: Evaluated value is equal to the top of the STACK
Step 6: Exit
Example
Let P=6, 5, 3, +, *, 12, 3, /, -
Initially add ‘#’ at the end of the given expression P
P=6, 5, 3, +, *, 12, 3, /, -,#
Now we will scan the symbols until ‘#’ is encountered.
Scanned Operation Stack
Line
Symbol performed
6 Push 6
1 6
5 Push 5
2 6 5
3 Push 3
3 6 5 3
+ Pop 3 and 5
4
5+3=8 6 8
Push 8
* Pop 8 and 6
5
6*8=48 48
Push 48
12 Push 12
6 48 12
3 Push 3
7 48 12 3
/ Pop 3 and
8
12
48 4
12/3=4
Push 4
- Pop 4 and
9
48
44
48-4=44
Push 44
Value of postfix expression=Top of stack= 44

SINDHI COLLEGE BANGALORE - 24


UNIT 2 Data Structures Using C 34

LINKED LIST REPRESENTATION OF STACKS


In a linked stack every node has two parts:
• One part stores data
• Another part stores the address of the next node.
The START pointer of the linked list is used as TOP. All insertions and deletions are done at
the node pointed by TOP. If TOP== NULL, then it indicated that the stack is empty
The pictorial representation of linked list representation of stack
TOP
2025 2025 2010 215
50 10 90 NULL

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.

SINDHI COLLEGE BANGALORE - 24


UNIT 2 Data Structures Using C 35

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

SINDHI COLLEGE BANGALORE - 24


UNIT 2 Data Structures Using C 36

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

Circular Priority Double Ended


Linear Queue
Queue 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

SINDHI COLLEGE BANGALORE - 24


UNIT 2 Data Structures Using C 37

Step 3: Insert the item


Q[REAR]= item
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 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;
}
}

SINDHI COLLEGE BANGALORE - 24


UNIT 2 Data Structures Using C 38

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)

SINDHI COLLEGE BANGALORE - 24


UNIT 2 Data Structures Using C 39

{
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

SINDHI COLLEGE BANGALORE - 24


UNIT 2 Data Structures Using C 40

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

2025 2010 215


50 10 90 NULL
To insert an element with value 80, we first 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 end of the linked
stack. The updated linked queue is shown below:
FRONT REAR

SINDHI COLLEGE BANGALORE - 24


UNIT 2 Data Structures Using C 41

2025 2010 215 1040


50 10 90 80 NULL

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

2025 2010 215 1040


50 10 90 80 NULL

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

2010 215 1040


10 90 80 NULL

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.

SINDHI COLLEGE BANGALORE - 24


UNIT 2 Data Structures Using C 42

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

Circular Queue Traversal


This operation access all the elements in the circular queue.
Algorithm CQDISPLAY(Q,FRONT,REAR,N)

SINDHI COLLEGE BANGALORE - 24


UNIT 2 Data Structures Using C 43

Step 1: If FRONT <= REAR


Display the array from Q[FRONT] to Q[REAR]
Step 2: IF FRONT > REAR
Display the array from Q[FRONT] to Q[N-1]
Display the array from Q[0] to Q[REAR]

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

Ascending Priority Queue Descending Priority Queue

 Ascending priority queue


In ascending priority queue, elements can be inserted in arbitrary order, but only
smallest can be deleted first.
 Descending priority queue
In descending priority queue, elements can be inserted in arbitrary order, but only the
largest element can be deleted first.
The representation of priority queue is shown below:
Suppose an array with elements 10, 5, 30, 20 and 80 in the same order, so, insertion can
be done with the same sequence, but the order of deleting the elements is 80, 30, 20,
10, 5 for descending priority queue and the order for deleting elements is 5, 10, 20, 30,
80 for ascending order

SINDHI COLLEGE BANGALORE - 24


UNIT 2 Data Structures Using C 44

Implementing a priority queue


The various ways of implementing a priority queue is as follows
• Using a simple linear array
• Using multi-queue implementation
Priority queue using arrays

 It is implemented in two ways


First Method
 Let insertion happen in FIFO like simple queue,
 For deletion, traverse the array for an element of the highest priority and then
delete this element from the queue.
 If this is not the front most element, then shift all its trailing elements to the left
side to fill up the vacant position.
Second Method
 Sort the inserted elements in ascending order
 Now delete the front element like in the simple queue.
Multi Queue Implementation
 The multi-queue implementation of a priority queue is similar to array implementation
except that
 A separate queue for each level of priority has to be maintained
 And each such queue represents a circular array.
 Number of priority levels used = number of queues to be used
 It is represented using a 2D array
 Two linear arrays FRONT[] and REAR[] are to be maintained to store Front
and Rear elements of each priority levels

SINDHI COLLEGE BANGALORE - 24


UNIT 2 Data Structures Using C 45

DEQUE (or, Double Ended 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:

Double Ended Queue

Input restricted deque Output restricted deque

 Input restricted deque


In input restricted queue, insertion operation can be performed at only one
end, while deletion can be performed from both ends.

 Output restricted deque


In output restricted queue, deletion operation can be performed at only one
end, while insertion can be performed from both ends.

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.

SINDHI COLLEGE BANGALORE - 24


UNIT 2 Data Structures Using C 46

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.

SINDHI COLLEGE BANGALORE - 24


UNIT 3 Data Structures Using C 1

Trees

Tree is a non-linear data structure.

Definition:

A tree is a finite set of one or more nodes such that

i)there is a special node called the root node.

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.

SINDHI COLLEGE BANGALORE - 24


UNIT 3 Data Structures Using C 2

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

Path − Path refers to sequence of nodes along the edges of a tree.

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:

A binary tree T is a finite set of nodes such that

i)T is empty or

ii)T contains a special node called root node and

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.

SINDHI COLLEGE BANGALORE - 24


UNIT 3 Data Structures Using C 3

Strictly Binary 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.

Full or Complete binary tree:

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.

Almost full Binary tree:

A binary tree of depth n is an almost complete binary tree if

i)any node at level less than n-1 has two children.

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.

SINDHI COLLEGE BANGALORE - 24


UNIT 3 Data Structures Using C 4

Memory representation of Binary Tree

A binary tree data structure is represented using two methods. They are:

1. Array Representation
2. Linked List Representation

Consider the following binary tree...

1. Array Representation of Binary Tree


In array representation of a binary tree, we use one-dimensional array (1-D Array) to represent
a binary tree.
Consider the above example of a binary tree and it is represented as follows:

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.

2. Linked List Representation of Binary Tree


To represent a binary tree, we use doubly linked list. In a double linked list, every node consists
of three fields. First field for storing left child address, second for storing actual data and third
for storing right child address.
In this linked list representation, a node has the following structure.

Example:

SINDHI COLLEGE BANGALORE - 24


UNIT 3 Data Structures Using C 5

Advantage

1. Insertion and deletion may be performed easily.

2. It allocates memory dynamically

Disadvantage

1. Extra memory is required to maintain the left link and right link pointers

Binary Tree Traversal:

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)

The following algorithm illustrates preorder traversal.

Algorithm:

Step1: Process the root node.


If root ≠ NULL then
Print ptr->info
Else
Print “Tree is empty”
Step 2: Traverse the left sub tree recursively in preorder
If ptr->left ≠ NULL

SINDHI COLLEGE BANGALORE - 24


UNIT 3 Data Structures Using C 6

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.

Step 1: It process the root node. It print 8


Step 2: Then it process the left link of 8, here it is 5.
Step 3: Then it process the left link of 5, here it is 9.
Step 4: Then it process the left link and right link of 9, here it is NULL.
Step 5: So it process the right link of 5, here it is 7.
Step 6: Recursively it call pre_order() until all the node has been visited.

The preorder traversal form of above binary tree is


8→ 5 → 9 → 7 → 1 → 12 → 2 → 4 → 11 → 3

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:

Step1: Check tree is empty


If root == NULL then
Print “Tree is empty”
Step 2: Traverse the left sub tree recursively in inorder
If ptr->left ≠ NULL
Call in_order(ptr->left)
Step 3: Process the root node.

SINDHI COLLEGE BANGALORE - 24


UNIT 3 Data Structures Using C 7

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.

The inorder traversal form of above binary tree is


9→ 5 → 1 → 7 → 2 → 12 → 8 → 4 → 3 → 11

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:

Step1: Check tree is empty


If root == NULL then
Print “Tree is empty”
Step 2: Traverse the left sub tree recursively in postorder
If ptr->left ≠ NULL
Call post_order(ptr->left)
Step 3: Traverse the right sub tree recursively in postorder
If ptr->right ≠ NULL

SINDHI COLLEGE BANGALORE - 24


UNIT 3 Data Structures Using C 8

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.

The postorder traversal form of above binary tree is


9→ 1 → 2 → 12 → 7 → 5 → 3 → 11 → 4 → 8

Binary search tree or Ordered Binary Tree


The Binary search tree is a binary tree in which each node has value
greater than every node of left sub tree and less than every node of right sub tree.

Operations on Binary search tree


The major operations on Binary search tree are listed
1. Insertion / Creation - Insert a node in binary search tree.
2. Searching – It search an item in a binary search tree.
3. Deletion – It delete a node from binary search tree.
4. Traversals – This operation visit all the nodes once in an order.
5. Finding maximum value in BST
6. Finding minimum value in BST
Insertion:
This operation is used to create or insert a node in binary search tree.
Write create() C code

Explanation

SINDHI COLLEGE BANGALORE - 24


UNIT 3 Data Structures Using C 9

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.

Height Balance: AVL Tree

• 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

Balance factor=Height(left sub tree) – Height (right sub tree)


SINDHI COLLEGE BANGALORE - 24
UNIT 3 Data Structures Using C 10

Balance factor values are {-1, 0, 1}

Operations on AVL Trees

• 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


• Right to Right rotation
• Left to Right rotation
• Right to Left rotation
The last two rotation are double rotation

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

SINDHI COLLEGE BANGALORE - 24


UNIT 3 Data Structures Using C 11

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

Insertion Operation in AVL Tree


In an AVL tree, the insertion operation is performed with O(log n) time complexity. In AVL
Tree, a new node is always inserted as a leaf node. The insertion operation is performed as
follows...

• 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

SINDHI COLLEGE BANGALORE - 24


UNIT 3 Data Structures Using C 12

Search Operation in AVL Tree


It refers to finding an element in an AVL tree. In an AVL tree, the search operation is performed
with O(log n) time complexity. The search operation in the AVL tree is similar to the search
operation in a Binary search tree.

Deletion Operation in AVL Tree


The deletion operation in AVL Tree is similar to deletion operation in BST. But after every
deletion operation, we need to check with the Balance Factor condition. If the tree is balanced
after deletion go for next operation otherwise perform suitable rotation to make the tree
Balanced.
Heap
A binary heap is a complete binary tree in which every node satisfies the heap properties.
Property 1: Nodes must be arranged in an order according to their values based on Max heap
or Min heap.
Property 2: All levels in a heap must be full except the last level and all nodes must be filled
from left to right strictly.
The two types of heap data structures are:
1. Max Heap
2. Min Heap
Max Heap
Max heap is a specialized full binary tree in which every parent node contains greater or equal
value than its child nodes.
Insertion Operation in Max Heap
Insertion Operation in max heap is performed as follows

• Step 1 - Insert the newNode as last leaf from left to right.

SINDHI COLLEGE BANGALORE - 24


UNIT 3 Data Structures Using C 13

• Step 2 - Compare newNode value with its Parent node.


• Step 3 - If newNode value is greater than its parent, then swap both of them.
• Step 4 - Repeat step 2 and step 3 until newNode value is less than its parent node (or)
newNode reaches to root.

Example
Construct a max heap tree with the given data values: 25, 35, 20, 10, 45, 70, 50

Deletion Operation in Max Heap

SINDHI COLLEGE BANGALORE - 24


UNIT 3 Data Structures Using C 14

The following steps are involved deleting a node from the heap tree

• Find the node that is to be deleted


• Take the last node of the tree at the place of deleted node
• Keep the node at the appropriate place using the following steps:
• Step 1 - Now, compare root value with its left child value.
• Step 2 - If root value is smaller than its left child, then compare left child with
its right sibling. Else goto Step 4
• Step 3 - If left child value is larger than its right sibling, then swap
root with left child otherwise swap root with its right child.
• Step 4 - If root value is larger than its left child, then compare root value with
its right child value.
• Step 5 - If root value is smaller than its right child, then swap root with right
child otherwise stop the process.
• Step 6- Repeat the same until root node fixes at its exact position.

Heap Sort
Heap sort is one of the sorting algorithms used to arrange a list of elements in order.

• Step 1 - Construct a Binary Tree with given list of Elements.


• Step 2 - Transform the Binary Tree into Min Heap.
• Step 3 - Delete the root element from Min Heap using Heapify method.
• Step 4 - Put the deleted element into the Sorted list.
• Step 5 - Repeat the same until Min Heap becomes empty.
• Step 6 - Display the sorted list.

Example

SINDHI COLLEGE BANGALORE - 24


UNIT 3 Data Structures Using C 15

SINDHI COLLEGE BANGALORE - 24


UNIT 3 Data Structures Using C 16

SINDHI COLLEGE BANGALORE - 24


UNIT 3 Data Structures Using C 17

Lexicographic Search Trees: Trie


Trie : Introduction

• The term trie came from the word retrieval.


• Trie data structure makes retrieval of a string from the collection of string more easily.
• Trie is also called as Prefix Tree or Digital Tree

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.

SINDHI COLLEGE BANGALORE - 24


UNIT 3 Data Structures Using C 18

• All the key values cannot be easily represented as strings.


• Example: 1 is equivalent to 1.0, 1.00, +1.0 etc

Applications of Trie

• To store a Dictionary
• Spell-checking software

External Searching: B-Trees

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

Example B-tree of order 4

B-Tree Operations

• Searching
• Insertion
• Deletion

B-Tree Operations: Insertion

SINDHI COLLEGE BANGALORE - 24


UNIT 3 Data Structures Using C 19

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

B-Tree Operations : Deletion

• Deletion of keys in a B-Tree


• First requires traversal
• After reaching a particular node, delete the node using any of the following case
1. Node is a leaf node
2. Node is not a leaf node

1. Node is a leaf node


1. If the node has more than minimum number of keys then deletion can be done easily

SINDHI COLLEGE BANGALORE - 24


UNIT 3 Data Structures Using C 20

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

2. Node is not a leaf node

• 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

SINDHI COLLEGE BANGALORE - 24


UNIT 3 Data Structures Using C 21

Application of B-Trees

• B-Trees are used to index the data especially in large databases


• Searching of data in larger unsorted data sets takes a lot of time but this can be
improved significantly with indexing using B-trees

Applications of trees

• Storing hierarchical data


• It is used to organize data for efficient insertion, deletion and searching
• Trie is a fast and efficient way for dynamic spell checking
• Heap is used to implement priority queues
• B-tree is used to implement indexing in databases

SINDHI COLLEGE BANGALORE - 24


?ll l RaDuaT ro^f To qRnehr aE Fr ril ll lo^l s

I qnyh.
qsarA q h -l
1.otur ) and a ao.t F o5
:+' ) b"la

t1 =Q,e ) , v D;h rht


va\hce\ E l)

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,

h c|'rcrtt "l a, d;c1-,yh , is a-


1
Gl = (v, c) Lrl^nc ',1 sat vaho* abmtth
oLlec( vo.yLiu., eis a da-t: X orh 'ad
oleft\lhtt @ t\/ vc\ti L? av al<o calk,'l &t
%
t,

flah,atts % t ar(t ' ot dtgttad "hf


Itr.r,o, q.0,e)
v, [, t,>,3,r
E - \:t,,1 (1,?) (3',r)'(4,1)

n* a -)v rl nrl ra. z a\ v)tl


3 un&ktttad qholh

t.d raFh t7. t\iE ) ,

\,1i\ a sa e(t mr nb cahd uct L.

rt a \a,l of oaducd par ts y ci sR.tt: ah fir bla


Y'
*z olt o uLh ol ,t, t
l.)
aa LhchQtfuil kl ,,1,,
w
4.Ha,a
l]vuo
fi=(v,e)
v.t, t,>,l,l,s| 5
E, q(1,1),( 1,1).(,,),O,A),(a, \
f+ Lt)v i:s 3atlt ,t! v.;LL

stba^df

,tTh whasc ,or hccr a"d


,f
1

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

-fr.r rp.ttifts f *d aljae*


i
,f ,j ) q*"rr -tF" )
I) 4a
l, irc icb at -rk \r1L,ct s t

1k c,Latc tcd edqt (i,j) L3 t n( i(@^t Lb

, .' -l vorh,
ru/1 t^t rclt h t i ,11

h rcrbr j aL.,l vort"x dl bh \ e.l h*


ll
4
4

F,ty { t,a) tr,". : a^d inti&ol b tt


6 an&
x*, ""1
tul
1" a 6livtr:d t, 4.. nr,b"-, e7 aely,
7,.(
l,,vo v a\ tfuit tot ^.te it c atbc,'l tr*
hr t fk
a,nba, otr dtr
i
"d,zgtu 't" T] init.nt .va"ltx is calb,l
ae tfu vcjbr v
I
an&q,ar (:) = r

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

-tn non- l",,rt k",l al, a 'tha d,X*t q ^


&tr,,, d b,l
I h Lttp t.Litkhr
VolDa
..u "J
ahv t aM ?ath otLtl n- un,
v inQ )s d, L f ,) A,1'
+k vet bx
I I
d, .(v)
I *J (r)=.: I

*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

r, o r tn,L -ifrc L{t$Pbta' ,,:itI" uothat rs &nbi


ll
k edXer
bY

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'

ri,j) ffura o..tth a path fi'an 1


h
t- ^rl; 6) "b

d.. I t, L , ltr., u. tr th"t +k


tt
slronXll co"ne tt "l
.

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

n rirn/)L Pfi 1".^ % f. v, L a pLA ha1,,


vc h Vn 'r,i6 nc Llaatd Yett'ct!
t t, 1,A,6,3) G,n,,t,e,o a, e1,s,at,q) -,si6pl, Fdlt'

lt,t,r,t,z, z) (a,a, 't,ot,,l,/ t,t, a) , L,2,3)- Lbt-


' sql
tL t'{b
, rl, h ic a t[,ra,l
gta'Li
"3 I
1_+ lrt3-54-)|
it ^ .,;Jch

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

61RFP.r Rt- pR E J6d.rA.1oN

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.

a^d r coh,nnt fatA tt 4k m"h, n lrltuqht' !


bab:uu" i an,'!
t ttu, o

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,,

a\atot,to,hur '1k a,*11 1L4h


^dlt:l ,

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

Directed Acyclic Graphs(DAG)

• It is a directed graph with no cycles

Articulation Points (or Cut Vertices) in a Graph

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

A graph is said to be Biconnected if:

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

SINDHI COLLEGE BANGALORE - 24


UNIT 3 Data Structures Using C 31

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

1. DFS (Depth First Search)


2. BFS (Breadth First Search)

DFS (Depth First Search)


Depth-first search (DFS) is an algorithm for traversing a graph data structures. The
algorithm starts at the root node and explores as far as possible along each branch before
backtracking. DFS(Depth First Search) uses Stack data structure
Procedure

1. Push starting node into the stack


2. Pop an element from the stack, if it has not been traversed then traverse it. If it has
already been traversed then just ignore it. (visited[i]=true)
3. Now push all the unvisited adjacent nodes of the popped element on to the stack. (push
if it is already on the stack)
4. Repeat step 3 and step 4 until stack is empty

Algorithm

SINDHI COLLEGE BANGALORE - 24


UNIT 3 Data Structures Using C 31

SINDHI COLLEGE BANGALORE - 24


UNIT 3 Data Structures Using C 31

SINDHI COLLEGE BANGALORE - 24


UNIT 3 Data Structures Using C 31

BFS (Breadth First Search)

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

1. Insert starting node into the queue


2. Delete front element from the queue and insert all its unvisited neighbours into the rear
end of the queue, and traverse them.(visited=true)
3. Repeat step 2 until queue is empty

Algorithm

SINDHI COLLEGE BANGALORE - 24


UNIT 3 Data Structures Using C 31

SINDHI COLLEGE BANGALORE - 24


UNIT 3 Data Structures Using C 31

SINDHI COLLEGE BANGALORE - 24


UNIT 3 Data Structures Using C 31

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

SINDHI COLLEGE BANGALORE - 24


UNIT 3 Data Structures Using C 31

SINDHI COLLEGE BANGALORE - 24


UNIT 3 Data Structures Using C 31

SINDHI COLLEGE BANGALORE - 24


UNIT 4 Data Structures Using C 1

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)

Complexity function f(n)

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.

SINDHI COLLEGE BANGALORE - 24


UNIT 4 Data Structures Using C 2

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

SINDHI COLLEGE BANGALORE - 24


UNIT 4 Data Structures Using C 3

Complexity of Bubble sort


In bubble sort, n-1 comparisons are made in pass1, n-2 comparisons in pass2, n-3
comparisons in pass 3 and so on.
Total number of comparisons = (n-1)+(n-2)+(n-3) +…..+3+2+1
= n(n-1)/2 (Sum of n-1 natural numbers)
which is of O(n2)
Hence the complexity of Bubble sort F(n) = O(n2)

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

SINDHI COLLEGE BANGALORE - 24


UNIT 4 Data Structures Using C 4

Algorithm of Selection Sort


SELECTION SORT(A[n]) // A is an array of elements to be sorted
Step 1: Set LOC = 0
Step 2: Repeat steps 3 and 4 for K=0 to n-1
Step 3: LOC = CALL MIN (A,K,n)
Step 4: [ Interchange A[K] and A[loc] ]
temp = A[K]
A[K] = A[LOC]
A[LOC] = temp
Step 5: Exit

Algorithm to find the smallest element in an array


MIN(A[n]) // A is an array of elements to be sorted
Step 1: Set MIN = A[K], LOC =K
Step 2: Repeat steps 3 for J=K+1 to n-1
Step 3: If MIN > A[j]
min = A[J]
LOC = J
End IF
Step 4: return LOC;
Program to sort the list of elements using selection sort
#include<stdio.h>
#include<conio.h>
int minimum(int a[], int k, int n)
{
int loc, j, min;
min= a[k];
loc= k;
for(j=k+1; j < n; j ++)
{
if( min > a[j])
{
min = a[j];
loc= j;
}
}
return loc;
}
void main()
{
int i, a[]= {75, 8, 1, 16, 68, 3, 7, 0}, k, n=8, loc=0, temp;
clrscr();
printf("The array before sorting is: \n");
for(i=0; i<n; i++)
{
printf("%d", a[i]);
}
for(k=0; k<n; k++)
{
loc = minimum(a, k, n);

SINDHI COLLEGE BANGALORE - 24


UNIT 4 Data Structures Using C 5

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

Complexity of selection sort


In selection sort, n-1 comparisons are made in pass1, n-2 comparisons in pass2, n-3
comparisons in pass 3 and so on.
Total number of comparisons = (n-1)+(n-2)+(n-3) +…..+3+2+1
= n(n-1)/2 (Sum of n-1 natural numbers)
which is of O(n2)
Hence the complexity of Selection sort F(n) = O(n2)

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

SINDHI COLLEGE BANGALORE - 24


UNIT 4 Data Structures Using C 6

SINDHI COLLEGE BANGALORE - 24


UNIT 4 Data Structures Using C 7

Program to sort the list of elements using insertion sort

Complexity of insertion sort


In insertion sort, n-1 comparisons are made in pass1, n-2 comparisons in pass2, n-3
comparisons in pass 3 and so on.
Total number of comparisons = (n-1)+(n-2)+(n-3) +…..+3+2+1
= n(n-1)/2 (Sum of n-1 natural numbers)
which is of O(n2)
Hence the complexity of Insertion sort F(n) = O(n2)

SINDHI COLLEGE BANGALORE - 24


UNIT 4 Data Structures Using C 8

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

SINDHI COLLEGE BANGALORE - 24


UNIT 4 Data Structures Using C 9

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)

SINDHI COLLEGE BANGALORE - 24


10
11
12
13
14
15
16
17
18
19
UNIT 4 Data Structures Using C 20

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.

Characteristics of Good hash function


1. Easy to Compute
2. Uniform distribution
3. Less collisions
4. High load factor
Hash Collision

SINDHI COLLEGE BANGALORE - 24


UNIT 4 Data Structures Using C 21

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 + ⋯ + 𝐾𝑛

SINDHI COLLEGE BANGALORE - 24


UNIT 4 Data Structures Using C 22

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

SINDHI COLLEGE BANGALORE - 24


UNIT 4 Data Structures Using C 23

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.

iii. Double probing


The generated address of a hash function ‘H’ is ‘a’ then in case of collision we will
again do the hashing of this hash function.
Disadvantage
• Requires two times calculation of hash function
iv. Rehashing
If hash table is full then we will use a new hash function and insert all the elements of
the previous hash table one by one and calculate the hash key with new hash function
and insert them into the new hash table. This technique is called rehashing.

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

SINDHI COLLEGE BANGALORE - 24


UNIT 4 Data Structures Using C 24

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

Operations on a chained hash table

• Insertion in a chained hash table


• Deletion from a chained hash table
• Searching in a chained hash table
Disadvantage of chaining
• Linked list requires extra pointer

SINDHI COLLEGE BANGALORE - 24

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy