DS Using C Programming Notes

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 96

SJR College of Science, Arts and Commerce Dept.

of Computer Science

Data Structures using C Programming

Unit - I
Introduction to Data Structures

Data :

It is a part of information and a values (character or numeric),or set of values represented by data is
stored temporarily in the program data area or stored permanently on a file in storage devices.

OR

Data is a collection f known facts, figures,images, text etc...

Example : student's name and its id are the data about the student.

Entity set :

Group of entity with similar properties forms an entity set.

Example: Student s an entity.

Field:
Field is a basic unit of information representing the attribute of an entity. It corresponds o attributes.

Record:

Record can be defined as the collection of various data items. OR

It is a collection of field values of a given entity. It corresponds o entities.

Example : the student entity, then its name, address, course and marks can be grouped together to form
the record for the student. It is classified according to their lengths:

Fixed Length Record:


All the records will contain equal number of fields with similar data items and the same amount of
space allocated for each record.

Variable Length Record:

All the records will contain equal number of fields with similar data items but available in different length
in size i.e, amount of space is varied for each record.

File:
I Sem BCA Data Structure Page 1
SJR College of Science, Arts and Commerce Dept. of Computer Science

A File is a collection of various records of one type of entity.It corresponds to entity set.

It contains number of records, to identify the records, one field is selected as primary key that helps to
uniquely identify the record in a file.

Example : if there are 60 students in the class, then there will be 20 records in the related file where
each record contains the data about each student's.

Data Structures:

The organized collection of data is known data structures.

Data structures=Organized data + Operations

Application of Data Structures:

It is used to retrieve he individual data elements.

It enables to solve the relationship between the data elements.

It describes the operation that must be performed on the logically related data elements.

It helps to reduce the loss of fragmentation and also allows to select the memory configuration or structure.
It gives the freedom to the programmer to decide any type of language that suits for particular problem.

It provides mode of access to each element in the data structures.

It describes the logical and physical relationship between the data items. It selects an appropriate

mathematical model for writing a program.

Classification of Data Structures:

The data structures are classified into two categories.

I Sem BCA Data Structure Page 2


SJR College of Science, Arts and Commerce Dept. of Computer Science

Primitive Data structure

The primitive data structures are primitive data types. The int, char, float, double, and pointer are the
primitive data structures that can hold a single value.

Non-Primitive Data structure

The non-primitive data structure is divided into two types:

• Linear data structure


• Non-linear data structure

Linear Data Structure :

The arrangement of data in a sequential manner is known as a linear data structure. The data structures

used for this purpose are Arrays, Linked list, Stacks, and Queues.
In these data structures, one element is connected to only one another element in a linear form.

Types of Linear Data Structures are :


Arrays:

An array is a collection of similar type of data items and each data item is called an element of the array .

The data type of the element may be any valid data type like char, int, float or double.

The elements of array share the same variable name but each one carries a different index number known
as subscript.

The array can be one dimensional, two dimensional or multidimensional. The individual elements of the

array age are:

age[0], age[1], age[2], age[3],..........age[98], age[99].

I Sem BCA Data Structure Page 3


SJR College of Science, Arts and Commerce Dept. of Computer Science

Linked List:

Linked list is a linear data structure which is used to maintain a list in the memory.

It can be seen as the collection of nodes stored at non- contiguous memory locations. Each node of the list

contains a pointer to its adjacent node.

Stack:

Stack is a linear list in which insertion and deletions are allowed only at one end, called top[LIFO]. A stack

is an abstract data type (ADT), can be implemented in most of the programming languages.

Example: - piles of plates or deck of cards etc.

I Sem BCA Data Structure Page 4


SJR College of Science, Arts and Commerce Dept. of Computer Science

Queue:

Queue is a linear list in which elements can be inserted only at one end called rear and deleted only at the
other end called front.

Queue is opened at both end therefore it follows First- In-First-Out (FIFO) methodology for storing the
data items.

Non Linear Data Structures:

This data structure does not form a sequence i.e. each item or element is connected with two or more
other items in a non-linear arrangement. The data elements are not arranged in sequential structure.

Types of Non Linear Data Structures are :


Trees:

Trees are multilevel data structures with a hierarchical relationship among its elements known as nodes.
The bottom most nodes in the hierarchy are called leaf node while the top most node is called root node.

Each node contains pointers to point adjacent nodes.


Tree data structure is based on the parent-child relationship among the nodes.

Each node in the tree can have more than one children except the leaf nodes whereas each node can have
atmost one parent except the root node.

I Sem BCA Data Structure Page 5


SJR College of Science, Arts and Commerce Dept. of Computer Science

Graphs:

Graphs can be defined as the pictorial representation of the set of elements (represented by vertices)
connected by the links known as edges.

A graph can form a cycle.

Operations on data structure :


Traversing:
Traversing the data structure means visiting each element of the data structure in order to perform some
specific operation like searching or sorting.

Example: If we need to calculate the average of the marks obtained by a student in 6 different subject, we
need to traverse the complete array of marks and calculate the total sum, then we will divide that sum by the
number of subjects i.e. 6, in order to find the average.
Insertion:

Insertion can be defined as the process of adding the elements to the data structure at any location. If the size
of data structure is n then we can only insert n-1 data elements into it.

Deletion:

The process of removing an element from the data structure is called Deletion. We can delete an element
from the data structure at any random location.
If we try to delete an element from an empty data structure then underflow occurs.

Searching:
The process of finding the location of an element within the data structure is called Searching. There are two
algorithms to perform searching, Linear Search and Binary Search.

I Sem BCA Data Structure Page 6


SJR College of Science, Arts and Commerce Dept. of Computer Science

Sorting:
The process of arranging the data structure in a specific order is known as Sorting. There are many

algorithms that can be used to perform s sorting.

Example: insertion sort, selection sort, bubble sort, merge sort, shell sort.

Merging:

When two lists List A and List B of size M and N respectively, of similar type of elements, joined to
produce the third list, List C of size (M+N), then this process is called merging.

I Sem BCA Data Structure Page 7


SJR College of Science, Arts and Commerce Dept. of Computer Science

Single Dimensional Array

Array
:

An array is defined as the collection of similar type of data items stored at contiguous memory locations.

For example, if we want to store the marks of a student in 6 subjects, then we don't need to define different
variables for the marks in the different subject. Instead of that, we can define an array which can store the
marks in each subject at the contiguous memory locations.

Advantage of Array:

1. Code Optimization: Less code to the access the data.

2. Ease of traversing: By using the for loop, we can retrieve the elements of an array easily.

3. Ease of sorting: To sort the elements of the array, we need a few lines of code only.

4. Random Access: We can access any element randomly using the array.

Disadvantage of Array :

1. Fixed Size: Whatever size, we define at the time of declaration of the array, we can't exceed the
limit. So, it doesn't grow the size dynamically like LinkedList which we will learn later.

Declaration of Array :

data_type array_name[array_size];

I Sem BCA Data Structure Page 8


SJR College of Science, Arts and Commerce Dept. of Computer Science

Eg : int marks[5];

Initialization of Array

The simplest way to initialize an array is by using the index of each element. We can initialize each
element of the array by using the index. Consider the following example.
marks[0]=80; //initialization of array marks[1]=60;
marks[2]=70; marks[3]=85; marks[4]=75;
OR
We can initialize the array at the time of declaration :
int marks[5]={80,60,70,85,75};
If there is no requirement to define the size:
int marks[]={20,30,40,50,60};

In 0 based indexing, If the size of an array is n then the maximum index number, an element can have is n-1.

Accessing Elements of an array


To access any random element of an array we need the following information:
1. Base Address of the array.
2. Size of an element in bytes.
3. Which type of indexing, array follows.
Address of any element of a 1D array can be calculated by using the following formula:
Byte address of element A[i] = base address + size * ( i - first index)

I Sem BCA Data Structure Page 9


SJR College of Science, Arts and Commerce Dept. of Computer Science

OR
address of element A[i] = base address + size * ( i )

In an array, A[-10......+2 ], Base address (BA) = 999, size of an element = 2 byte s,


find the location of A[-1].
L(A[-1]) = 999 + [(-1) - (-10)] x 2
= 999 + 18
= 1017
Eg : #include<stdio.h> int main()
{
int i=0;
int marks[5];//declaration of array marks[0]=80;//initialization of array marks[1]=60;
marks[2]=70; marks[3]=85; marks[4]=75;
//traversal of array for(i=0;i<5;i++)
{
printf("%d \n",marks[i]);
}//end of for loop return 0;
}

Program without array:


#include <stdio.h>
void main ()
{
int marks_1 = 56, marks_2 = 78, marks_3 = 88, m arks_4 = 76, marks_5 = 56, marks_6 = 89; float
avg = (marks_1 + marks_2 + marks_3 + m arks_4 + marks_5 +marks_6) / 6 ; printf(avg);
}

Program by using array:


#include <stdio.h>
void main ()
{
int marks[6] = {56,78,88,76,56,89};
int i;
float avg;
for (i=0; i<6; i++ )
{
avg = avg + marks[i];
}
printf(avg);
}

I Sem BCA Data Structure Page 10


SJR College of Science, Arts and Commerce Dept. of Computer Science

Multi Dimensional Array


Two Dimensional Array:
• 2D array can be defined as an array of arrays. The 2D array is organized as matrices which can be
represented as the collection of rows and columns.
• 2D arrays are created to implement a relational database look alike data structure. It provides ease
of holding bulk of data at once which can be passed to any number of functions wherever required.
How to declare 2D Array
The syntax of declaring two dimensional array is very much similar to that of a one dimensional array,
given as follows.
int arr[max_rows][max_columns];
The syntax of declaring two dimensional array is very much similar to that of a one dimensional array,
given as follows.
1. int arr[max_rows][max_columns];

The elements are organized in the form of rows and columns. First element of the first row is represented by
a[0][0].

How do we access data in a 2D array


The elements of 2D arrays can be random accessed. Similar to one dimensional arrays, we can access the
individual cells in a 2D array by using the indices of the cells. There are two indices attached to a
particular cell, one is its row number while the other is its column number.

However, we can store the value stored in any particular cell of a 2D array to some variable x by using
the following syntax.
int x = a[i][j];

I Sem BCA Data Structure Page 11


SJR College of Science, Arts and Commerce Dept. of Computer Science

where i and j is the row and column number of the cell respectively.

1. for ( int i=0; i<n ;i++)


2. {
3. for (int j=0; j<n; j++) 4. {
5. a[i][j] = 0;
6. }
7. }

Initializing 2D Arrays
int arr[2][2] = {0,1,2,3};

The number of elements that can be present in a 2D array will always be equal to (number of rows *
number of columns).

Example : Storing User's data into a 2D array and printing it.


1. #include <stdio.h>
2. void main () 3. {
4. int arr[3][3],i,j;
5. for (i=0;i<3;i++)
6. {
7. for (j=0;j<3;j++)
8. {
9. printf("Enter a[%d][%d]: ",i,j);
10. scanf("%d",&arr[i][j]);
11. }
12. }
13. printf("\n printing the elements\n");
14. for(i=0;i<3;i++)
15. {
16. printf("\n");
17. for (j=0;j<3;j++)
18. {
19. printf("%d\t",arr[i][j]);
20. }
21. }
22. }

Mapping 2D array
The storage technique for 2D array is similar to that of an one dimensional array.

to map two dimensional array to the one dimensional array in order to store them in the memory.

I Sem BCA Data Structure Page 12


SJR College of Science, Arts and Commerce Dept. of Computer Science

A 3 X 3 two dimensional array is shown in the following image.However, this array needs to be mapped
to a one dimensional array in order to store it into the memory.

There are two main techniques of storing 2D array elements into memory:

1. Row Major Representation:


In this, all the rows of the 2D array are stored into the memory contiguously. Its memory allocation
according to row major order is shown as follows.

first, the 1st row of the array is stored into the memory completely, then the 2nd row of the array is stored into
the memory completely and so on till the last row.

2. Column Major ordering:


In this, all the columns of the 2D array are stored into the memory contiguously.

first, the 1st column of the array is stored into the memory completely, then the 2nd row of the array is stored
into the memory completely and so on till the last column of the array.

By Row Major Order:


I Sem BCA Data Structure Page 13
SJR College of Science, Arts and Commerce Dept. of Computer Science

If array is declared by a[m][n] where m is the number of rows while n is the number of columns, then
address of an element a[i][j] of the array stored in row major order is calculated as,

1. Address(a[i][j]) = Base Address + (i * (colsize) + j) * si ze


where, base address or the address of the first element of the array a[0][0] .

Example :
1. a[10...30, 55...75], base address of the array (BA) = 0, si ze of an element = 4 bytes .
2. Find the location of a[15][68].
3. Address(a[15][68]) = 0 + ((15 - 10) x (68 -55 + 1) + (68 - 55)) x 4
4. = (5 x 14 + 13) x 4
5. = 83 x 4
6. = 332 answer

By Column major order:


If array is declared by a[m][n] where m is the number of rows while n is the number of columns, then
address of an element a[i][j] of the array stored in row major order is calculated as,
Address(a[i][j]) = ((j*m(rowsize))+I )*Size + BA where BA is the base address of the array.
Example:
1. A [-5 ... +20][20 ... 70], BA = 1020, Size of element = 8 byt es. Find the location of a[0][30]. 2.
Address [A[0][30]) = ((30-20) x 24 + 5) x 8 + 1020
= 245 x 8 + 1020 = 2980 bytes.

Matrix addition and subtraction Matrix addition:


Matrix addition Algorithm
Here is A two dimensional array with M rows and N columns and B is a two dimensional array with X
rows and Y columns.

Step 1: if (M!= X) or (N!= Y) then Print addition is not possible Exit() Step 2: Repeat for i=1 to M
Step 3: repeat for j= 1 to N
Step 4: set C [i] [j ] = A [i] [j] + B[i] [j] End of step 3and 4 for loop
Step 5: Exit()

Matrix subtraction Algorithm


Here is A two dimensional array with M rows and N columns and B is a two dimensional array with X
rows and Y columns.
Step 1: if (M!= X) or (N!= Y) then Print Subtraction is not possible Exit() Step 2: Repeat for i=1 to M
Step 3: repeat for j= 1to N
Step 4: set C [i] [j ] = A [i] [j] - B[i] [j] End of step 3and 4 for loop

I Sem BCA Data Structure Page 14


SJR College of Science, Arts and Commerce Dept. of Computer Science

Step 5: Exit()

Write a program to find the addition and subtraction of a matrix

#include <stdio.h> int main()


{
int A[10][10], B[10][10] , i ,j ,m, n ,x , y;
printf(" \n enter number of rows and columns for Matrix A:") scanf("%d", &m,&n);
printf(" \n enter number of rows and columns for Matrix B:") scanf("%d", &x,&y);
if(m!=n || n!=y)
{
printf("\n Addition and Subtraction is not possible"); return 0;
}
for(i=0; i<m; i++) for(j=0; j<n; j++)
{
printf(" \n enter the element [%d][%d] of A:",i+1, j+1); scanf("%d", &A[i][j]);
}
for(i=0; i<x; i++) for(j=0; j<y; j++)
{
printf(" \n enter the element [%d][%d] of B:",i+1, j+1); scanf("%d", &B[i][j]);
}
printf("\n A\t\t B\t\t Sum \t\t Sub\n\n"); for(i=0; i<m; i++)
{
for(j=0; j<n; j++) printf("%3d" , A[ i ][ j ]); printf ("\t\t");
for(j=0; j<n; j++) printf("%3d" , B[ i ][ j ]); printf ("\t\t");
for(j=0; j<n; j ++)
printf("%3d" , A[ i ][ j ] +B[ i ][ j ] ); printf ("\t\t");
for(j=0; j<n; j++)
printf("%3d" , A[ i ][ j ] - B[ i ][ j ] ); printf ("\t\t");
}
return 0;
}

Matrix Multiplication Algorithm


Here is A two dimensional array with M rows and N columns and B is a two dimensional array with X
rows and Y columns.
Step 1: if (M!= Y) or (N!= X) then
Print Multiplication is not possible Exit()
Step 2: Repeat for i=1 to N
Step 3: repeat for j= 1to X
Step 4: set C [i] [j ] = 0

I Sem BCA Data Structure Page 15


SJR College of Science, Arts and Commerce Dept. of Computer Science

Step 5: repeat for K= 1 to Y


Step 6 : C [i] [j ] = C [i] [j ] + A [i] [j] * B[i] [j]
End of step 5, 3and 2 for loop
Step 5: Exit()

Write a program to find the multiplication of two matrix


#include <stdio.h> int main()
{
int A[10][10], B[10][10] ,C[10][10] , i ,j ,m, n ,x , y;
printf(" \n enter number of rows and columns for Matrix A:") scanf("%d", &m,&n);
printf(" \n enter number of rows and columns for Matrix B:") scanf("%d", &x,&y);
if(m!=y || n!=x)
{
printf("\n Multiplication is not possible"); return 0;
}
for(i=0; i<m; i++) for(j=0; j<n; j++)
{
printf(" \n enter the element [%d][%d] of A:",i+1, j+1); scanf("%d", &A[i][j]);
}
for(i=0; i<x; i++) for(j=0; j<y; j++)
{
printf(" \n enter the element [%d][%d] of B:",i+1, j+1); scanf("%d", &B[i][j]);
}
for(i=0; i<n; i++) for(i=0; j<x; j++)
{
C[i][j] = 0
for(k=0; k<y; k++)
C [i] [j ] = C [i] [j ] + A [i] [j] * B[i] [j]
printf ("\t\t");
}
printf("\n \ t product of the matrices isb\n" ); for(i=0; i<m; i++)
{
for(j=0; j<y; j++) printf("%d" , C[ i ][ j ] ); printf ("\t\n\t");
}
return 0;
}

Sparse Matrices

It is a matrices which contains more number of zero element then non- zero element.

I Sem BCA Data Structure Page 16


SJR College of Science, Arts and Commerce Dept. of Computer Science

Here,it contains only 8 non- zero element and 32 zero element.


It requires 40× 4(data type size)= 160 bytes

Write a program to check whether given matrix is sparse matrix or not


# include <stdio.h> int main( )
{
int matrix [ 10][10]; int i,j,m,n;
int sparse_counter =0;
printf("enter the order of the matric\n"); scanf("%d % d",& m,&n);
printf (" enter the element of the matrix");
for(i=0; i< m; ++i)
{
for(j=0; j< n ; ++j)
{
scanf("%d",& matrix [i][j]); if(matrix [i][j] ==0)
{
++sparse_counter;
}
}
}
if(sparse_counter > ((m *n)/2))
{
printf ("the given matrix is sparse matrix\n");
}
else
printf (" the given matrix is not a spare matrix\n"); printf ("there are %d number of
zeros",spare_counter); getch();
}

Transpose a Sparse Matrix


Transpose of a matrix is obtained by changing rows to columns and columns to rows. In other words,
the transpose of A[][] is obtained by changing A[i][j] to A[j][i].

I Sem BCA Data Structure Page 17


SJR College of Science, Arts and Commerce Dept. of Computer Science

Write a program in C to find the transpose of a given matrix.


#include <stdio.h> void main()
{
int arr1[50][50],brr1[50][50], i, j, r, c;
printf("\n\nTranspose of a Matrix :\n");
printf("--------------------------\n");
printf("\nInput the rows and columns of the matrix : ");
scanf("%d %d",&r,&c);
printf("Input elements in the first matrix :\n");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
printf("element - [%d],[%d] : ",i,j);
scanf("%d",&arr1[i][j]);
}
}
printf("\nThe matrix is :\n"); for(i=0;i<r;i++)
{
printf("\n"); for(j=0;j<c;j++);
printf("%d\t",arr1[i][j]);
}
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
brr1[j][i]=arr1[i][j];
}
}
printf("\n\nThe transpose of a matrix is : ");
for(i=0;i<c;i++)
{
printf("\n"); for(j=0;j<r;j++)
{
printf("%d\t",brr1[i][j]);
}
}
printf("\n\n");
}

Output:
I Sem BCA Data Structure Page 18
SJR College of Science, Arts and Commerce Dept. of Computer Science

Transpose of a Matrix
Input the rows and columns of the matrix : 2 2 Input elements in the first matrix :
element - [0],[0] : 1
element - [0],[1] : 2
element - [0],[1] : 3
element - [1],[1] : 4 The matrix is :
1 2
3 4

The transpose of a matrix is :

1 3
2 4

Write a program to transpose a sparse matrix


#include<studio.h>
#include<conio.h>
int main()
{
int A [ 10][10], i, j, sparse [10][3], transpose[10][3]m, n, s=0;
printf("enter the order m x n of the sparses matric\n");
scanf("%d % d",& m,&n);
printf (" enter the element in the sparses the matrix");
for(i=0; i< m; i++)
for(j=0; j< n ; j++) scanf("%d",& A [i][j]);
printf("the given matrix is:");
for(i=0; i< m; i++)
{
for(j=0; j< n ; j++)
{
printf(%d",A [i][j]);
}
printf("\n");
}
for(i=0; i< m; i++)
{
for(j=0; j< n ; j++)
{
if(A [i][j] !=0)
{
sparse[s][0]=i;
sparse[s][1]=j;
sparse[s][2]=A[i][j] ;
transpose[s][0]=j; transpose[s][1]=i;

I Sem BCA Data Structure Page 19


SJR College of Science, Arts and Commerce Dept. of Computer Science

transpose[s][2]=A [i][j] ;
s++;
}
}
}
printf ("the given matrix is sparse matrix\n");
printf("\n");
for(i=0; i< s; i++)
{
for(j=0; j< 3 ; j++)
{
printf(%d",sparses [i][j]);
}
printf("\n");
}
printf ("the given matrix is transpose matrix\n");
printf("\n");
for(i=0; i< s; i++)
{
for(j=0; j< 3 ; j++)
{
printf(%d",transpose [i][j]);
}
printf("\n");
}
getch();
}

I Sem BCA Data Structure Page 20


SJR College of Science, Arts and Commerce Dept. of Computer Science

Unit-II
Linked List

Dynamic Memory Allocation :

There are two types of memory


allocation

1) Static Memory Allocation or Compile Time :

• In this allocation the memory required to the variable is at the time of compilation.

• Allocated memory is fixed.

Eg ,: int i, j;

2) Dynamic Memory Allocation or Run Time :

• The process of allocating memory during the execution of the program. (OR)

• The process of allocating memory to the variable at the run-time.

• It is used when we are not aware of the memory requirements.

• It is used in linked list

Some of the function used are :

□ malloc() - it allocates the requested memory space and returns a pointer at the first byte of allocated
memory space.

o It is declared in <stdlib.h>

o Syntax : ptr= (cast-type*) malloc(byte-size);

o Eg : int arr= (int*) malloc (10*sizeof(int));

□ Pointer : A pointer is a variable that stores the address of another variable. pointer holds the address
of a variable. the variables that are used to store the location of value present in the memory. A
pointer to a location stores its memory address.

o The data type of pointer and the variable must match, an int pointer can hold the address of
int variable.

o It is defied as *

I Sem BCA Data Structure Page 21


SJR College of Science, Arts and Commerce Dept. of Computer Science

□ calloc() - it is used to request multiple blocks of storage each of same size and the value stored in
the allocated memory space is zero by default. It isused to allocate memory for array.

o Syntax : ptr=(cast-type*)calloc(n,elem-size);

o Eg: int *ip;

ip=(int*)calloc(100,sizeof(int));

□ free() - deallocates the previously allocated memory space by malloc ,calloc or realloc functions.

o Syntax : free(ptr);

o Eg: free(ptr)

o Any pointer pointing to a destroyed object or which doesn't contain a valid address is
called as dangling pointer .

□ realloc() - Alters the size of memory allocated previously. The new size can be larger or smaller.

o If the block is larger then the old contents remains unchanged and memory is added at end
of the block.

o If the size is small then the contents are unchanged.

o If it can't be resized the realloc assign a new block of memory and will copy the
old contents to it.

o It takes 2 arguments,the first is pointer referencing the memory and second is total number
of bytes that reallocate.

o If memory can't reallocate then it returns NULL pointer.

o Syntax : ptr = realloc(ptr,newsize);

o Eg: ip =( int *) realloc(ip,500);

Static Memory Allocation & Dynamic Memory Allocation:

static memory allocation dynamic memory allocation

1. memory is allocated at compile time. 1. memory is allocated at run time.

2. memory can't be increased while executing 2. memory can be increased while executing
program. program.

3. used in array. 3. used in linked list.

I Sem BCA Data Structure Page 22


SJR College of Science, Arts and Commerce Dept. of Computer Science

Linked List :
o It can be defined as collection of objects called nodes that are randomly stored in the memory.
o A node contains two fields i.e. data stored at that particular address and the pointer which
contains the address of the next node in the memory.
o The last node of the list contains pointer to the null. (OR )

✔ Data : this field is used to store the data or information .

✔ Link : this field contains address of the next node.

✔ External pointer : it is named as start ,it is a pointer to the very first node in the linked list ,it enables
us to access the entire Linked List. Ji

Definition : It is a collection of zero or more nodes where each node has some information.

As per the above illustration :

● Linked List contains a link element called first.

● Each link carries a data field(s) and a link field called next.

● Each link is linked with its next link using its next link.

● Last link carries a link as null to mark the end of the list.

Advantages of Linked List

❖ optimized utilization of space : The list is not required to be contiguously present in the
memory. The node can reside any where in the memory and linked together to make a list.

❖ list size : it is limited to the memory size and doesn't need to be declared in advance.

❖ Empty node: it can not be present in the linked list.

● We can store values of primitive types or objects in the singly linked list.

● It allocates the memory dynamically.

I Sem BCA Data Structure Page 23


SJR College of Science, Arts and Commerce Dept. of Computer Science

Linked list is the data structure which can overcome all the limitations of an array :

● It allocates the memory dynamically.


● All the nodes of linked list are non-contiguously stored in the memory and linked together
with the help of pointers.
● Sizing is no longer a problem since we do not need to define its size at the time of declaration.
● List grows as per the program's demand and limited to the available memory space.

Applications of linked list:


1. Linked lists are used to represent and manipulate polynomial. Polynomials are expression containing
terms with non zero coefficient and exponents.
For example: P(x) = a0 X n + a1 X n-1 + …… + an-1 X + an
2. Represent very large numbers and operations of the large number such as addition, multiplication and
division.
3. Linked lists are to implement stack, queue, trees and graphs.
4. Implement the symbol table in compiler construction.

Representation of a Linked List in Memory

There are two ways to represent a linked list in memory:

1. Static representation using array

2. Dynamic representation using free pool of storage

1. Static representation

● In static representation of a single linked list, two arrays are maintained: one array for data and
the other for links.

Eg : A single linked list with six nodes.


● Two parallel arrays of equal size are allocated which should be sufficient to store the entire
linked list.
● One major problem is that the size of an array must be specified at the beginning.

2. Dynamic representation of linked list

● The process of allocating memory at runtime is known as dynamic memory allocation.

● In this the node is created dynamically whenever it is required depending upon the requirement.

● To create a linked list structure is to be declared that defines all the list of entities.

I Sem BCA Data Structure Page 24


SJR College of Science, Arts and Commerce Dept. of Computer Science

● This structure is capable of holding the data and the address of the memory space holding the
next structure in the list.

● The link member field contained in the structure node which is used to point to the same
structure type of is called self referential structure.

● A node may contain any number of information fields.

Structure:

□ Structure in c is a user-defined data type that enables us to store the collection of different data
types.
□ Each element of a structure is called a member.
□ struct keyword is used to define the structure.
Syntax:
struct structure_name
{
data_type member1; data_type member2;
.
.
data_type memeberN;
};

Here, struct is the keyword; employee is the name of the structure; id, name, and salary are the members
or fields of the structure.

I Sem BCA Data Structure Page 25


SJR College of Science, Arts and Commerce Dept. of Computer Science

There are two ways to declare structure variable:

□ By struct keyword and declaring the object within main() function


Example :
struct employee
{
int id;
char name[50]; float salary;
};
□ By declaring a variable at the time of defining the structure.
struct employee
{
int id;
char name[50];

float salary;
}e1,e2;

Types of linked list

1. Singly linked list


2. Circular linked list
3. Doubly linked list
4. Header linked list

Singly linked list

● It is also known as one way list .

I Sem BCA Data Structure Page 26


SJR College of Science, Arts and Commerce Dept. of Computer Science

● It is a linear collection of data elements called notes where each node is divided into two parts in
4 field and link field the last node of link field is always point to NULL.

● In this for accessing any node of linked list we start travelling from first node, because it travels
only in one direction up to the last node.

Circular linked list

In circular linked list the link part of the last node points to the first node of the linked list and represent
the linked list in circular way.i.e the last node of link field holds the address of the first node.

The circular List can be traversed to any node from any node, because its direction is just like a circle.

Doubly linked list

It is also known as 2 way list called doubly linked list, where we can move in either forwarded and
backward direction.

Forward direction means traversing from left to right and backward direction means traversing from right
to left.

It is divided into three fields

□ Pointer to previous node/back field : which points to the previous node in the list or contains
the address of previous node. In this first not always contains null it indicates that it is the first node

□ Information field : this field holds the data or information.

□ Pointer to next node / forward field : this field points to the next node in the list or contains

I Sem BCA Data Structure Page 27


SJR College of Science, Arts and Commerce Dept. of Computer Science

the address of next node in the list. In this last node contains null indicating that it is the last node.

Header linked list

• It is a linked list which always in 4 contains a special node called the header node at the beginning of
the list.
• The header not contains the global information of the entire list i.e number of nodes present in the
list an address of the last node.

There are two kinds header linked list

1. Grounded header linked list.


2. Circular header linked list.

1. Grounded header linked list :

★ It is also referred as singly header linked list, here the header is not counted.

Circular header Linked list :

★ In this the last node points to the header node.


★ The the info field of header node contains the number of nodes in the linked list.

I Sem BCA Data Structure Page 28


SJR College of Science, Arts and Commerce Dept. of Computer Science

★ The length of the linked list can also be obtained from the info of header node.

★ If we insert a node into a linked list the info value of the header node should be incremented and if
we delete it should be decremented.

Notation of algorithms

Notation in algorithm C-Implementation Meaning


Start Start Pointer containing
the address of first node
CURRPTR=start CURRPTR=start Now start contains the address
of first node and stores the
address of first node in another
pointer called
CURRPTR
INFO [CURRPTR] CURRPTR->INFO The info field of the node is
now pointed by CURRPTR
LINK [CURRPTR] CURRPTR- Now current node
>LINK is pointing to the link field ud
so it is always a pointer address
of
the next node
INFO [LINK [CURRPTR]] CURRPTR->LINK->INFO The CURRPTR of the link field
no pointing to the next node
INFO [CURRPTR]=ITEM CURRPTR->INFO=ITEM Stores the item into the
information field of the current
node
LINK[CURRPTR]= CURRPTR->LINK=NEWNODE It makes the link between the
NEWNODE CURRPTR node with a
NEWNODE.It contains
the address of the NEWNODE
start=LINK [start] start=start->LINK Start pointing to the second

I Sem BCA Data Structure Page 29


SJR College of Science, Arts and Commerce Dept. of Computer Science

note show the address of the S


note is now stored in the start.
This is used to delete the first
node.
start=getnode(); start=(NODE*)malloc(sizeof(NODE)) Creates a node with the
; specified size and address of
that known is stored in start
NEWNODE=getnode(); NEWNODE=(NODE*)malloc Creates a new node and
(sizeof(NODE))); allocates the specified memory
space to that node
free(start); free(start); Deallocate the memory of start

free(CURRPTR); free(CURRPTR); Deallocate the memory of


CURRPTR

GETNODE and FREENODE operations[Memory Allocation] :


• getnode ():
It is used for creating a node, after allocating memory for the node, if we have a finite
number of nodes that are available then we have to delete a node by calling getnode operation, so it
remove the first node from the availability list and point to the second node.

By using AVAIL=AVAIL->LINK

NEWNODE=getnode () If(AVAIL==NULL)
{

printf("overflow") exit(1);
}
NEWNODE=AVAIL;
AVAIL=AVAIL->LINK;

• freenode():
This operations remove any node from the existing linked list and add it to the front of the
availability list.

NEWNODE->LINK=AVAIL AVAIL=NEWNODE

Garbage Collection :
• It is a automatic memory management of dynamically allocated storage.
• Reclaim unused blocks or memory occupied by the object or pointers that are no longer in use
by program.
• It is a block of heap memory that cannot be accessed by the program
I Sem BCA Data Structure Page 30
SJR College of Science, Arts and Commerce Dept. of Computer Science

Operations on single linked list

The basic operations to be performed on a single linked list are:

1) creating a linked list:

This operation is used to create a linked list, and number of nodes that contains information field and link
field where the last node of the link field is to be made as NULL.

Algorithm

Step 1: create first node and assign the address of first node to the pointer start.
start=getnode();

Step 2: use another pointer to store the address of the first node called CURRPTR(used for traversing)
CURRPTR = start;

Step 3: accept the element and store it in the info field of the first node.
INFO [CURRPTR] =ITEM;

Step 4: accept the choice whether to create another node or not


if( choice='Y')
goto step 5
else
goto step 6

I Sem BCA Data Structure Page 31


SJR College of Science, Arts and Commerce Dept. of Computer Science

Step 5 : if choice is Yes create another node


NEWNODE = getnode(); ( It contains the address of the newly created node)
LINK [CURRPTR] = NEWNODE; (link between the last node and Newnode)

CURRPTR = NEWNODE (address of Newnode is assigned to the currptr)

INFO[CURRPTR]= ITEM( Storing the element in the info field of currptr)


Goto step 4

Step 6: if choice is No then make Link field of last node to NULL LINK [CURRPTR]= NULL

I Sem BCA Data Structure Page 32


SJR College of Science, Arts and Commerce Dept. of Computer Science

Step 7: return

Function to create linked list


void createlist(int n)
{
int i;
node * new node;
node *temp;
for(i = 0; i < n ; i+ +)
{
new node = getnode();
if(start = = NULL)
{
start = new node;
}
else
{
temp = start;
while(temp - > next != NULL)
temp = temp - > next
tem p - > next = new node;

}
}
}

Traversing a linked list

• Traverse a list in order to process each node exactly once from the first node to the end of the list.
• Considered pointer variable CURRPTR that points to the note currently being processed.

Algorithm
I Sem BCA Data Structure Page 33
SJR College of Science, Arts and Commerce Dept. of Computer Science

o STEP 1: SET PTR = HEAD


o STEP 2: IF PTR = NULL
Write Empty List”
GOTO STEP 7
END IF
o STEP 4: REPEAT STEP 5 AND 6 UNTIL PTR != NULL
o STEP 5: PRINT PTR→ DATA
o STEP 6: PTR = PTR → NEXT
[END OF LOOP]
o STEP 7: EXIT

Displaying a linked list


o To display a linked list in our order we can process each node exactly once and display the elements
in the info field starting from the first node to the end of the list.

Length operation

It is used to find the number of elements or nodes in the given linked list. If the linked list is empty then it
returns 0
It traverse the list from start to end

Searching a linked list

Which is used to search a particular element in the list.


We have to compare each element of the list with the required element until the element is found.
If the element is found the searchers successful and IT returns the location of the node otherwise it returns
null.

Insertion of a Node:
One of the most primitive operations that can be done in a singly linked list is the insertion of a node.
Memory is to be allocated for the new node (in a similar way that is done while creating a list) before
reading the data. The new node will contain empty data field and empty next field.
The data field of the new node is then stored with the information read from the user.
The next field of the new node is assigned to NULL.

The new node can then be inserted at three different places namely:
• Inserting a node at the beginning.
• Inserting a node at the end.

I Sem BCA Data Structure Page 34


SJR College of Science, Arts and Commerce Dept. of Computer Science

• Inserting a node at intermediate position.

Inserting a node at the beginning:


The following steps are to be followed to insert a new node at the beginning of the list:
• Get the new node using getnode(). newnode = getnode();
• If the list is empty then start = newnode.
• If the list is not empty, follow the steps given below:
newnode -> next = start;
start = newnode;
Figure .shows inserting a node into the single linked list at the beginning.

Figure. Inserting a node at the beginning

The function insert_at_beg(), is used for inserting a node at the beginning


void insert_at_beg()
{
node *newnode;
newnode = getnode();
if(start == NULL)
{
start = newnode;
}
else
{
newnode -> next = start;
start = newnode;
}
}

Inserting a node at the end:

The following steps are followed to insert a new node at the end of the list:

• Get the new node using getnode() newnode = getnode();

• If the list is empty then start = newnode.

• If the list is not empty follow the steps given below:


I Sem BCA Data Structure Page 35
SJR College of Science, Arts and Commerce Dept. of Computer Science

temp = start; while(temp -> next != NULL) temp = temp -


> next;
temp -> next = newnode;

The function insert_at_end(), is used for inserting a node at the end.

void insertatend()
{
node *newnode, *temp;
newnode = getnode();
if(start == NULL)
{
start = newnode;

}
else
{

temp = start;
while(temp -> next != NULL) tem= temp -> next;
temp -> next = newnode;

}
}

I Sem BCA Data Structure Page 36


SJR College of Science, Arts and Commerce Dept. of Computer Science

Stack
STACK :
A stack is a list of elements in which an element may be inserted or deleted only at one end,
called the top of the stack. Stacks are sometimes known as LIFO (last in, first out) lists.

As the items can be added or removed only from the top i.e. the last item to be added to a stack is the
first item to be removed.

The two basic operations associated with stacks are:

• Push: is the term used to insert an element into a stack.


• Pop: is the term used to delete an element from a stack.

Operation on Stack:

1) Push operation

Let Stack is considered has “S” that contains MAXSTK( maximum number of items present in stack)

Algorithm

Push(S,Top, MAXSTK,item)
If the stack is empty the Top is set to -1
Step 1: check weather stack is overflow
If Top=MAXSTK-1
then(stack is overflow)
return
Step 2: now increment the value of Top
Top = Top+1
Step 3: insert the item at the top
S[Top]= item
Step 4 : return

2) Pop operation
Step 1: check weather stack is underflow
If Top=-1
then(stack is overflow)
Exit()
Step 2: delete the item present in stack
Item =S[Top]
Step 3: decrement the top value
Top = Top-1
Step 4 : exit()

I Sem BCA Data Structure Page 37


SJR College of Science, Arts and Commerce Dept. of Computer Science

3) Display operation
Algorithm
Step 1: check weather stack is empty
if Top==-1
then(stack is empty)
else
the contents of the stack is displayed from the top of the stack till the bottom of the
stack.
for(i=Top; i>=0; i--)
print S[i]

4) isempty operation
It is used to find whether the stack contains any element or not .
Is the stack is empty then it returns True(1), else if stack is not empty bthen it returns False(0).
It is mainly used for checking Underflow.
Algorithm
Step 1: if (Top== -1)
return (True)
else
return (False)

5) Stacktop() operation or Peek operation


It is used to get the top element of the stack without Removing from the stack .
Step 1: if (Top== -1)
print (stack underflow)
else
return (S[Top])

Linked List Representation of Stacks

Linked stack every known as 2 parts one that stores data and other that stores the address of the next node this
Start pointer of the linked list is used as Top.
All insertion and deletion are done at the node pointed by top.
If top is Null then it indicate the stack is empty

1) Push Operation
It is used to insert an element into the stack
The new element is added at the topmost position of the stack

Algorithm to insert an element in a linked stack

Step 1: allocate memory for the new node and name it as NEWNODE
Step 2: set Info [NEWNODE]= item
Step 3: if Top= NULL

I Sem BCA Data Structure Page 38


SJR College of Science, Arts and Commerce Dept. of Computer Science

Set LINK [NEWNODE]=Null


Set Top= NEWNODE
else
Set LINK [NEWNODE]= Top
Set Top= NEWNODE
Step 4: end

2) Pop operation
It is used to delete the topmost element / node from an stack
Algorithm
Step 1: check weather the top is Null
if Top=NULL
print underflow
Goto step 5
Step 2: set CURRPTR= Top
Step 3: set Top= Top-> Nextnode
Step 4: Free (CURRPTR)
Step 5: end

3) Display operation
Algorithm
Step 1: if Top=Null
print Stack is empty
else
while CURRPTR!=NULL
Info[CURRPTR]
LINK [CURRPTR]
Step 2: Exit

Recursion :
o It is the process of calling the function repeatedly by itself is called as Recursion.
o The recursive function calls are pushed on to the stack until the condition is satisfied.
o Once the condition is terminated the function pushed into the stack are popped from the stack one
after the other.
Properties for satisfying the recursive function
1) The function must have a stopping condition.

2) Each time the function should call by itself,i.e it must be recursive form. Untill you the the solution or
the condition is satisfied.

Types of Recursion
1) Direct
2) Indirect
1) Direct :
I Sem BCA Data Structure Page 39
SJR College of Science, Arts and Commerce Dept. of Computer Science

In this type of recursion the function calls itself repeatedly until certain condition is satisfied.
fact(int n) // repeatedly called with fact (n-2)
{
if(n==1)
return 1
else
return(n*fact(n-1));
}

2) Indirect:

In this type of recursion the function calls another function which eventually causes the
same function to be called, that is the function indirectly calls itself through another function.
Fun1(int a)
{
Fun2(b);
}
Fun2(int b)
{
Fun1(b-1);
}

1) Introductory : Save the local variables and return address.

2) Body of the Function : if stopping condition is reached go to concluding part, otherwise


process the instruction and go to introductory.

3) Concluding part : get recently saved local variables and parameters and return address from
the stack.

Advantages of recursion

1) It reduces the complexity of the problem

I Sem BCA Data Structure Page 40


SJR College of Science, Arts and Commerce Dept. of Computer Science

2) It allows the user to write much simpler and elegant program.


3) The program implemented by recursion will be smaller in length.
4) The program can have any number of nesting levels.
5) This technique is more natural and compact.
6) It is a top down programming tool where the given problem is divided into to smaller models and each
models are individually attached later.

Finding Factorial
Given positive integer ‘n’ the factorial has the product of all integers between ‘n’ and ‘1’.
It is denoted by by !.

Example :
Find the factorial of 5
5!= 5*4*3*2*1= 120
0!=1
In general n!=1 if n==0
n!= n *(n-1)*(n-2)*..............*1 if n>0

There are two ways to describe the factorial


1) Iterative description

2) Recursive description

Iterative Recursive
It is a bottom up approach where it can It is a top down approach where the given
construct the solution step by step program is divided into modules
It is an non-natural approach It is an natural approach
It takes less is execution time It takes considerable execution time
The programs have larger code length The programs have shorter code length

Find the factorial using iterative description is


Algorithm
Step 1: fact = 1
Step 2: for (i = 1 to N)
fact = 1* fact
Step 3: return (fact)
Step 4: End

Find the factorial using recursive description


Algorithm
Step 1: if (N=0) then
fact = 1. // Terminate condition
Step 2: else
fact = N * fact(N-1)
Step 3: return (fact)

I Sem BCA Data Structure Page 41


SJR College of Science, Arts and Commerce Dept. of Computer Science

Step 4: End

Fibonacci series:
It is a series of integer where each element in the series is the sum of the two preceding elements
Example :
0,1,1,2,3,5,8,13,21..........................so on
In this the first two elements will be 0,1as there is no 2 element behind them So start from 3 element
F1 = 0
F2 = 1
F3 = F2+F1 = 1+0= 1
F4 = F3+F2 = 1+ 1 = 2
F 5 = F4+ F3 ,= 2+ 1= 3
F6 = F5+F4 = 3+ 2= 5 and so on...
In general
Fib(N) = 0 ,1 , fib(N-1)+fib(N-2)
Algorithm
Step 1: if (( N == 0. ) || (N == 1)) then
fib = 0
Step 2: else if (N == 2) then
fib = 1
Step 3: else if (N > 2) then
Fib = Fibno(N -1)+Fibno( N-2)
Step 4: return (fib)
Step 5: end

I Sem BCA Data Structure Page 42


SJR College of Science, Arts and Commerce Dept. of Computer Science

Tower of Hanoi Problem:


o The tower of Hanoi is a mathematical puzzle.
o It consists of three rods and a number of disks of different sizes which can slide onto any rod.
o The puzzle starts with the disks in a neat stack in ascending order of size on one rod, the smallest at the
top.
o We have to obtain the same stack on the third rod.
The objective of the puzzle is to move the entire stack to another rod, obeying the following simple rules−
1. Only one disk can be moved at a time.
2. Each move consists of taking the upper disk from one of the stacks and placing. It on top of another
stack i.e. a disk can only be moved if it is the uppermost disk on a stack.
3. No disk may be placed on top of a smaller disk.
Algorithm
Step 1: if (n> 0)
Toh(n-1, S,D,T)
Step 2: Count ++
Toh( n-1,T,S,D)

Example
#include <stdio.h>
void TOH(int n,char x,char y,char z)
{
if(n>0)
{
TOH(n-1,x,z,y);
printf(" %c to %c",x,y);
TOH(n-1,z,y,x);
}
}
int main()
{
int n=3;
TOH(n,'A','B','C');
}
Output :
A to B
A to C

I Sem BCA Data Structure Page 43


SJR College of Science, Arts and Commerce Dept. of Computer Science

B to C
A to B
C to A
C to B
A to B

GCD
In general
GCD(m,n)= GCD(n,m) if n>m
m If n=0 (0, 5)
GCD (n,mod(m,n))

Modulo is what remainder will u get when u divided M by n


1) GcD(m,n)=GCD (n mod(m,n))

2) GCD (m,0)= m

GCD (48,18) where m=48, n= 18

Step 1: Now divide 48 by 18= 12=r


Step 2: GCD (18,12)
Now divide 18 by 12 = 6= r
Step 3: GCD (12,6)
Now divide 12 by 6. = 0
GCD (6,0)= 6

Algorithm
Step 1: if (n==0)
Return (m)
Step 2: else if (n>m)
Return (GC D(n,m))
Step 3: else
Return(GCD(n, mod(m,n))

Arithmetic Expressions
o The way to write arithmetic expression is known as a notation.
o An arithmetic expression can be written in three different but equivalent notations, i.e., without
changing the essence or output of an expression.
These notations are –
1. Infix Notation
2. Prefix (Polish) Notation
3. Postfix (Reverse-Polish) Notation

I Sem BCA Data Structure Page 44


SJR College of Science, Arts and Commerce Dept. of Computer Science

Infix Notation
o We write expression in infix notation, e.g. a - b + c, where operators are used inbetween operands.
o It is easy for us to read, write, in infix notation but the same does not go well with computing devices.
o An algorithm to process infix notation could be difficult and costly in terms of time and space
consumption.
Prefix Notation
o In this notation, operator is prefixed to operands, i.e. operator is written ahead of operands.
o For example, +ab.
o This is equivalent to its infix notation a + b.
o Prefix notation is also known as Polish Notation.
Postfix Notation
o This notation style is known as Reversed Polish Notation.
o In this notation style, the operator is postfixed to the operands i.e., the operator is written after the
operands. For example, ab+.
o This is equivalent to its infix notation a + b.
The following table briefly tries to show the difference in all three notations

I Sem BCA Data Structure Page 45


SJR College of Science, Arts and Commerce Dept. of Computer Science

Unit-III
Queue
Queue
1. A queue can be defined as an ordered list which enables insert operations to be performed at one end
called REAR and delete operations to be performed at another end called FRONT.
2. Queue is referred to be as First In First Out list or Last In Last Out.
For example: people waiting in line for a rail ticket form a queue.

Applications of Queue
There are various applications of queues

1. Queues are widely used as waiting lists for a single shared resource like printer, disk, CPU.
2. Queues are used in asynchronous transfer of data (where data is not being transferred at the same rate
between two processes) for eg. pipes, file IO, sockets.
3. Queues are used as buffers in most of the applications like MP3 media player, CD player, etc.
4. Queue are used to maintain the play list in media players in order to add and remove the songs from
the play-list.
5. Circular Queues are used in operating systems for handling interrupts.
6. Quese are used in network communication system.

Operation on Queues :
1) Insertion(enqueue):
o It is to insert an element into an queue.
o The element is inserted at the Rear end,and the Rear will be incremented by 1.
o By default the Rear will be set to -1.
o If the queue is full it displays the is Overflow.
Algorithm
Step 1: check whether it is overflow
if Rear = N-1
Then display “Overflow”
return

I Sem BCA Data Structure Page 46


SJR College of Science, Arts and Commerce Dept. of Computer Science

Step 2 : increment rear


Rear = Rear +1
Step3: insert the element
Q[Rear]= item
Step 4: return
2) Deletion (dequeue):
Deleting the element from the queue.it delete from the front end.if the queue is empty and u are
trying to delete an element then it displays underflow.by default the Front is set to 0.

Algorithm
Step 1: check weather it is underflow
if Rear = Front -1
Then display “Underflow”
return
Step 2: deleting the element from an queue
Item =Q[Front]
Step3 : if there is only one element in Queue
If Front= Rear
else
Front = Front+1
Step 4: return

3) Queue isEmpty :
If the queue is empty then it returns 1 and if the queue is not empty it returns 0
Algorithm
Step 1: if Rear =Front-1
Return 1
else
return 0
4) Queue full:
If the queue is full it returns 1 and if the queue is not full it returns 0
Algorithm
Step 1: if Rear =N-1
return 1
else
return 0

5) Display:
It displays the items present in a queue
Algorithm
Step 1: check weather queue is empty
if(Rear==Front-1)
Display “Queue is empty “
Step 2: else

I Sem BCA Data Structure Page 47


SJR College of Science, Arts and Commerce Dept. of Computer Science

For(i=Front;i=<Rear;i++)
Display Queue [i]
Step 3: return

Circular Queue:
Ø A circular queue is similar to a linear queue as it is also based on the FIFO (First In First Out) principle
except that the last position is connected to the first position in a circular queue that forms a circle. It is
also known as a Ring Buffer.
Ø There was one limitation in the array implementation of Queue.
Ø If the rear reaches to the end position of the Queue then there might be possibility that some vacant
spaces are left in the beginning which cannot be utilized.
Ø So, to overcome such limitations, the concept of the circular queue was introduced.

Ø Here Front =3, Rear= 4 and N= 5


Ø When Rear Reaches N-1
Ø the rear is at the last position of the Queue and front is pointing to the 3rd position.
Ø In the above array, there are only two elements and other three positions are empty.
Ø The rear is at the last position of the Queue; if we try to insert the element then it will show that there
are no empty spaces in the Queue.
Ø The efficient approach to avoid the wastage of the memory or space is to use the circular queue data
structure.

Operations on Circular Queue


1. Insertion :
Algorithm
The steps of enqueue operation are given below:
o First, we will check whether the Queue is full or not.
o Initially the front and rear are set to -1. When we insert the first element in a Queue, front and
rear both are set to 0.
o When we insert a new element, the rear gets incremented, i.e., rear=rear+1.
Step 1: IF FRONT =(REAR+1)%N
Write " OVERFLOW "

I Sem BCA Data Structure Page 48


SJR College of Science, Arts and Commerce Dept. of Computer Science

Goto step 4
[End OF IF]
Step 2: to insert an element first check weather the queue is empty or not
if FRONT = -1 and REAR = -1
SET FRONT = REAR = 0
ELSE IF
REAR = N - 1 and FRONT ! = 0
SET REAR = 0
ELSE
SET REAR = (REAR + 1) % N (to increment rear position)
[END OF IF]

Step 3: SET QUEUE[REAR] = Item


Step 4: EXIT

2. Deletion
Algorithm
The steps of dequeue operation are given below:
o First, we check whether the Queue is empty or not. If the queue is empty, we cannot perform
the dequeue operation.
o When the element is deleted, the value of front gets decremented by 1.
o If there is only one element left which is to be deleted, then the front and rear are reset to -1.
Step 1: check queue is empty
IF FRONT = -1
Write " UNDERFLOW "
Goto Step 4
[END of IF]

Step 2:if queue is not empt,now Delete the item in Queue


SET item = QUEUE[FRONT]
Step 3: if there is only one element
IF FRONT = REAR
After deleting set Front and Rear to -1
SET FRONT = REAR = -1
ELSE IF
FRONT = N -1
SET FRONT = 0
ELSE
SET FRONT = (FRONT + 1)%N(increment the value of Front)
[END of IF]
[END OF IF]
Step 4: EXIT
Example of Circular Queues

I Sem BCA Data Structure Page 49


SJR College of Science, Arts and Commerce Dept. of Computer Science

Rear =Rear+1%N
0+1%5

Rear+1%N
Rear = 4+1%5= 5%5=0

I Sem BCA Data Structure Page 50


SJR College of Science, Arts and Commerce Dept. of Computer Science

3. Display:
Algorithm
Step 1: Check queue is empty
if(Front=-1)
Display “Queue is empty”
Step 2: else
if(front<=Rear)
for(i=front;i<=rear;i++)
Display Queue [i]
if(front>rear)
for(i=front;i<=N-1;i++)
Display Queue [i]
for(i=0;i<=rear;i++)
Display Queue [i]

Representation of Linked list in Queue


o If the queue is empty then the Front and Rear is set NULL
o Start pointer is pointing to the Front

Operation on Linked Queue


1. Insertion
Algorithm
Step 1: INFO [NEWNODE] = item
Step 2: if Front =NULL
Set Front =Rear=NEWNODE
Set Front ->Link=Rear->Link=NULL
else
I Sem BCA Data Structure Page 51
SJR College of Science, Arts and Commerce Dept. of Computer Science

Set Rear ->Link=NEWNODE


Set Rear =NEWNODE
Set Rear->Next(LINK)=Null
Step 4: exit

2. Delete
Algorithm
Step 1: if Front = NULL
Display “Empty”
Goto to last step
Step 2: set CURRPTR=Front
Step 3: set Front =Front [LINK]
Step 4: Free=CURRPTR
Step 5: Exit

Priority Queue:
There are 2 types
1) Ascending Priority Queue
2) Descending Priority Queue

Ascending Priority Queue


The element in the queue can be inserted in any order,but the deletion is done from the smallest element in the
queue.
10 ,40,50,5,2

Descending Priority Queue


The element in the queue can be inserted in any order,but the deletion is done from the largest element in the
queue.

There are various way to implement the priority Queue


1) By using simple linear array
2) By using multi queue

By using simple linear array


Ø We can insert the element in any order
Ø If we are using Ascending priority Queue.
Ø Then there is a 2ways to delete the element from a queue
1) Traverse the array element in the queue starting from the front till you find the highest priority
(smallest element) now you delete the smallest element from the queue, annd shift other
elements to its left side to occupy the space.
10 20 30 40 50
10,20,30,40,50
Algorithm
Deletion

I Sem BCA Data Structure Page 52


SJR College of Science, Arts and Commerce Dept. of Computer Science

Step 1: if(Rear=Front-1)
Display Queue is empty
Step 2: if there is only one element in the queue
else If(Rear=Front)
Delete Queue[Front]
Step 3: else
Min=Queue [0]
Index =0
For(i=0;i<rear;i++)
If(min>queue [i+1])
Min=queue [i+1]
Index= i+1
Delete Queue [index]
Step 4: for(i=index;i<rear;i++)
Queue [i]=Queue [i +1]
Rear --
Step 5: Return

2) While(temp>=0)&&(item<queue[temp]))
Queue[temp+1]=queue [temp]
Temp--
Queue[temp+1]=item
Rear++
Multi Queue
1. Insertion
Algorithm
Step 1: check weather the queue is full or not
If Rear[priority]=N-1
Display “Queue is overflow”
Step 2: increment rear by 1
Rear[priority] =Rear[priority]+1
Step 3: insert element into queue
Queue[priority][Rear[priority]]=item
2. Deletion
Algorithm
Step 1: check whether the queue is empty
If Rear[priority]=Frontr[priority]-1
Display “Underflow”
Step 2: delete the element from the front
Front[priority]++

Deques:
o This also known as Double-ended Queue.

I Sem BCA Data Structure Page 53


SJR College of Science, Arts and Commerce Dept. of Computer Science

o Deque is a linear data structure in which the insertion and deletion operations are performed from both
ends.
There are 2 types
1. Input Restricted Deque
2. Output Restricted Deque

Input Restricted Deque


o The insertion is done at the Rear end,but the deletion can be done at both ends that at Front and Rear.

Output Restricted Deque


o The insertion can be done on both Rear and Front end,but the deletion can be done only at the Front
end
Insertion
Algorithm To insert at rear end
Step 1: if(Front==(Rear+1)%N)
Display Queue Overflow
Step 2: insert an element into deque
else
First check the queue is empty
if(Front==-1)
Display Queue is empty
Set Front =Rear=0
else
Now we have to increment the rear position and insert an element into deque
Rear= (Rear+1)%N
Queue [Rear]=item

Insertion at the Front End


Algorithm
Step 1: if(Front==(Rear+1)%N)
Display Queue Overflow
Step 2: insert an element into deque
Else
First check the queue is empty
If(Front==-1)
Display Queue is empty
Set Front =Rear=0
Else If(Front ==0)
Front=N-1
Now we have to decrement the Front position and insert an element into deque of the Front
position
Else
Front= (Front-1)%N
Queue [Front]=item

I Sem BCA Data Structure Page 54


SJR College of Science, Arts and Commerce Dept. of Computer Science

Deleting an item from front end


Step 1: check queue is empty
If(Front==-1)
Display Queue is underflow
Else
Delete item from front
Item=Queue [Front]
Step 2: if there is only one element
If(Front==Rear)
Set Front=Rear=-1
Else
Increment the front value
Front=(Front+1)%N

Deleting an item from Rear End


Step 1: check queue is empty
If(Front==-1)
Queue is underflow
Else
Delete item from Rear
Item=Queue [Rear]
Step 2: if there is only one element
If(Front==Rear)
Set Front=Rear=-1
If(Rear ==0)
After deleting it should point to N-1
Rear=N-1
Else
Decrement rear value by 1
Rear=(Rear-1)%N

I Sem BCA Data Structure Page 55


SJR College of Science, Arts and Commerce Dept. of Computer Science

Unit – IV

Searching and Sorting


Searching Technique

o Searching is the process of finding some particular element in the list.


o If the element is present in the list, then the process is called successful, and the process returns the
location of that element. Otherwise, the search is called unsuccessful.
The two popular searching techniques are.
1. Linear Search
2. Binary Search
Here we will discuss the Binary Search Algorithm.

1) Binary Search Algorithm :

o Binary search is the search technique that works efficiently on sorted lists.
o Hence, to search an element into some list using the binary search technique, we must ensure that
the list is sorted.
o Binary search follows the divide and conquer approach in which the list is divided into two halves,
I Sem BCA Data Structure Page 56
SJR College of Science, Arts and Commerce Dept. of Computer Science

and the item is compared with the middle element of the list.
o If the match is found then, the location of the middle element is returned.
o Otherwise, we search into either of the halves depending upon the result produced through the match.

Note : Binary search can be implemented on sorted array elements. If the list elements are not arranged
in a sorted manner, we have first to sort them.

Algorithm

Binary_Search(a, lower_bound, upper_bound, val) // 'a' is the given array, 'lower_bound' is the index of the
first array element, 'upper_bound' is the index of the last array element, 'val' is the value to search

Step 1: set beg = lower_bound, end = upper_bound, pos= - 1

Step 2: repeat steps 3 and 4 while beg <=end


Step 3: set mid = (beg + end)/2
Step 4: if val =a[mid] set pos = mid + 1
print pos
go to step 6
else if val < a[mid]
set end = mid - 1
else
set beg = mid + 1 [end of if]
[end of loop]
Step 5: if pos = -1
print "value is not present in the array" [end of if]
Step 6: exit

Working of Binary search

✔ let's take a sorted array. It will be easy to understand the working of Binary search with an example.

✔ Let the elements of array are –

✔ Let the element to search is, K = 56

✔ We have to use the below formula to calculate the mid of the array - mid = (beg + end)/2

✔ So, in the given array - beg = 0 , end = 8 mid = (0 + 8)/2 = 4.

✔ So, 4 is the mid of the array.

I Sem BCA Data Structure Page 57


SJR College of Science, Arts and Commerce Dept. of Computer Science

✔ Now, the element to search is found. So algorithm will return the index of the element matched.

Binary search using 2 technique


1) Iterative
2) Recursive

I Sem BCA Data Structure Page 58


SJR College of Science, Arts and Commerce Dept. of Computer Science

I Sem BCA Data Structure Page 59


SJR College of Science, Arts and Commerce Dept. of Computer Science

Program: Write a program to implement Binary search in C language.

#include <stdio.h>
int binarySearch(int a[], int beg, int end, int val)
{
int mid;
if(end >= beg)
{ mid = (beg + end)/2;
/* if the item to be searched is present at middle */ if(a[mid] == val)
{
return mid+1;
}
/* if the item to be searched is smaller than
middle, then it can only be in left subarray */
else if(a[mid] < val)
{
return binarySearch(a, mid+1, end, val);
}
/* if the item to be searched is greater than middle, then it can only be in right subarray */ else
{
return binarySearch(a, beg, mid-1, val);
}
}
return -1;
}
int main()
{
int a[] = {11, 14, 25, 30, 40, 41, 52, 57, 70}; // given array
int val = 40; // value to be searched

I Sem BCA Data Structure Page 60


SJR College of Science, Arts and Commerce Dept. of Computer Science

int n = sizeof(a) / sizeof(a[0]); // size of array


int res = binarySearch(a, 0, n-1, val); // Store result
printf("The elements of the array are - ");
for (int i = 0; i < n; i++)
printf("%d ", a[i]);
printf("\nElement to be searched is - %d", val);
if (res == -1)
printf("\nElement is not present in the array");
else printf("\nElement is present at %d position of array", res);
return 0;
}

Binary Search complexity:

❑ Best Case Complexity - In Binary search, best case occurs when the element to search is found in first
comparison, i.e., when the first middle element itself is the element to be searched. The best-case time
complexity of Binary search is O(1).

❑ Average Case Complexity - The average case time complexity of Binary search is O(logn).

❑ Worst Case Complexity - In Binary search, the worst case occurs, when we have to keep reducing the
search space till it has only one element. The worst-case time complexity of Binary search is O(logn).

2)Linear Search Algorithm


✔ Linear search is also called as sequential search algorithm.
✔ It is the simplest searching algorithm.
✔ In Linear search, we simply traverse the list completely and match each element of the list with the
item whose location is to be found.
✔ If the match is found, then the location of the item is returned; otherwise, the algorithm returns NULL.
✔ It is widely used to search an element from the unordered list, i.e., the list in which items are not sorted.

The steps used in the implementation of Linear Search are listed as follows -
o First, we have to traverse the array elements using a for loop.
o In each iteration of for loop, compare the search element with the current array element. If the element
matches, then return the index of the corresponding array element.
o If the element does not match, then move to the next element.
o If there is no match or the search element is not present in the given array, return -1.

Algorithm
Linear_Search(a, n, val) // 'a' is the given array, 'n' is the size of given array, 'val' is the value to search

Step 1: set pos = -1


Step 2: set i = 0
Step 3: repeat step 4 while i <= n

I Sem BCA Data Structure Page 61


SJR College of Science, Arts and Commerce Dept. of Computer Science

Step 4: if a[i] == val set pos = i // key found at ith element.


print pos
go to step 6 [end of if]
set i = i + 1 [end of loop]
Step 5: if pos = -1
print "value is not present in the array " [end of if]
Step 6: exit

Working of Linear search


✔ Now, let's see the working of the linear search Algorithm.

✔ To understand the working of linear search algorithm, let's take an unsorted array.

✔ It will be easy to understand the working of linear search with an example.


✔ Let the elements of array are -

✔ Let the element to be searched is K = 41


✔ Now, start from the first element and compare K with each element of the array.

✔ The value of K, i.e., 41, is not matched with the first element of the array.
✔ So, move to the next element. And follow the same process until the respective element is found.

✔ Now, the element to be searched is found.

I Sem BCA Data Structure Page 62


SJR College of Science, Arts and Commerce Dept. of Computer Science

✔ So algorithm will return the index of the element matched.

Linear Search complexity


❑ Best Case Complexity - In Linear search, best case occurs when the element we are finding is at the
first position of the array. The best-case time complexity of linear search is O(1).
❑ Average Case Complexity - The average case time complexity of linear search is O(n).
❑ Worst Case Complexity - In Linear search, the worst case occurs when the element we are looking
is present at the end of the array. The worst-case in linear search could be when the target element is
not present in the given array, and we have to traverse the entire array. The worst-case time
complexity of linear search is O(n).

Program: Write a program to implement linear search in C language.

#include <stdio.h>

int linearSearch(int a[], int n, int val) {

// Going through array sequencially


for (int i = 0; i < n; i++)
{
if (a[i] == val) return i+1;
}
return -1;
}
int main() {
int a[] = {70, 40, 30, 11, 57, 41, 25, 14, 52}; // given array
int val = 41; // value to be searched
int n = sizeof(a) / sizeof(a[0]); // size of array
int res = linearSearch(a, n, val); // Store result
printf("The elements of the array are - ");
for (int i = 0; i < n; i++) printf("%d ", a[i]);
printf("\nElement to be searched is - %d", val);
if (res == -1)
printf("\nElement is not present in the array");
else
printf("\nElement is present at %d position of array", res); return 0;
}

Sorting :

▪ Sorting is a process of ordering or placing a list of elements from a collection in some kind of order.
▪ It is nothing but storage of data in sorted order. Sorting can be done in ascending and descending
order.

I Sem BCA Data Structure Page 63


SJR College of Science, Arts and Commerce Dept. of Computer Science

▪ It arranges the data in a sequence which makes searching easier.

Sorting can be performed using several techniques or methods, as follows:

O(nlogn) to O(n2)

1. Bubble Sort
2. Insertion Sort
3. Selection Sort
4. Shell Sort
5. Merge Sort
6. Quick Sort

1) Bubble Sort
 Bubble sort is a type of sorting.
 It is used for sorting 'n' (number of items) elements.
 It compares all the elements one by one and sorts them based on their values.

Passes n-1 N=5


Pass 1:
A[0] and A[1] 40> 10 interchange it .
A[1] and A[2] 40 > 20 swap
A[2] and A[3]40> 30 swap
A[3] and A[4] 40< 50

Example 2 : 28,20,30,15,05
Pass1 :
28>20 swap
20,28,30,15,05
28<30 no swaping

I Sem BCA Data Structure Page 64


SJR College of Science, Arts and Commerce Dept. of Computer Science

20,28,30,15,05
30 >15 swap
20,28,15,30,05
30 > 05
20,28,15,05,30
Pass2:
20,28,15,05,30
20<28 no swap
28 >15 swap
20,15,28,05,30
28 >05swap
20,15,05,28,30
28 < 30
20,15,05,28,30

Pass 3 :
20,15,05,28,30
20 >15swap
15,20,05,28,30
20>05 swap
15,5,20,28,30

Pass 4:
15,5,20,28,30
15>05 swap
5,15,20,28,30

▪ The above diagram represents how bubble sort actually works.

• This sort takes O(n2) time. It starts with the first two elements and sorts them in ascending order.

• Bubble sort starts with first two elements.

• It compares the element to check which one is greater.

• In the above diagram, element 40 is greater than 10, so these values must be swapped.

• This operation continues until the array is sorted in ascending order.

Program for Bubble Sort

#include <stdio.h>
void bubble_sort(long [], long);
int main()
{
long array[100], n, i, d, swap;
printf("Enter Elements\n");
scanf("%ld", &n);

I Sem BCA Data Structure Page 65


SJR College of Science, Arts and Commerce Dept. of Computer Science

printf("Enter %ld integers\n", n);


for (i = 0; i < n; i++)
scanf("%ld", &array[i]);
bubble_sort(array, n);
printf("Sorted list in ascending order:\n");
for ( i = 0 ; i < n ; i++ )
printf("%ld\n", array[i]);
return 0;
}
void bubble_sort(long list[], long n)
{
long i, d, t;
for (pass= 1 ; pass< n ; pass++)
{
for (j = 0 ; j < n - pass - 1; j++)
{
if (a[j] > a[j+1])
{
/* Swapping */
temp = a[j];
a[j]= a[j+1];
a[j+1] = temp;
}
}
}
}

2) Insertion Sort
Insertion sort is a simple sorting algorithm.
 This sorting method sorts the array by shifting elements one by one. It builds the final sorted array one
item at a time.
 Insertion sort has one of the simplest implementation. It requires single additional memory space.
 Insertion sort does not change the relative order of elements with equal keys because it is stable.
Eg :
A[1] is compared with A[0] i.e 10<40 Shifting and Insertion is done at A[0]
A[2] is compared with A[0] 9<10 A[3] is compared with A[0] 20> 9
A[3] is compared with A[1] 20> 10
A[3] is compared with A[2] 20<40
A[4] is compared with A[0] 30< 9
A[4] is compared with A[1] 30< 10
A[4] is compared with A[2] 30< 20

I Sem BCA Data Structure Page 66


SJR College of Science, Arts and Commerce Dept. of Computer Science

A[4] is compared with A[3] 30< 40

• Insertion sort works like the way we sort playing cards in our hands. It always starts with the second
element as key.
• The key is compared with the elements ahead of it and is put it in the right place. In the above figure,
40 has nothing before it.
• Element 10 is compared to 40 and is inserted before 40.
• Element 9 is smaller than 40 and 10, so it is inserted before 10 and this operation continues until the
array is sorted in ascending order.
Algorithm
Step :1 Repeat step 2 to 5For 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] = K
Step 6 : exit

Program for Insertion Sort

#include <stdio.h>
int main()
{
int n, array[1000], c, d, t;
printf("Enter number of elements\n");
scanf("%d", &n);
printf("Enter %d integers\n", n);

I Sem BCA Data Structure Page 67


SJR College of Science, Arts and Commerce Dept. of Computer Science

for (c = 0; c < n; c++)


{
scanf("%d", &array[c]);
}
for (pass = 1 ; pass <= n ; pass++)
{
K= a[Pass ];
for (j= pass-1;j>=0&&K<a[j];j--)
while ( d > 0 && array[d] < array[d-1])
{
t= array[d];
array[d]= array[d-1];
array[d-1] = t;
d--;
}
}
printf("Sorted list in ascending order:\n"); for (c = 0; c <= n - 1; c++)
{
printf("%d\n", array[c]);
}
return 0;
}

3) Selection Sort
• Selection sort is a simple sorting algorithm which finds the smallest element in the array and
exchanges it with the element in the first position.

• Then finds the second smallest element and exchanges it with the element in the second position
and continues until the entire array is sorted.

I Sem BCA Data Structure Page 68


SJR College of Science, Arts and Commerce Dept. of Computer Science

Pass 1 : A[2] 9 is the smallest element,this element is exchanged with 40 i.e A[2] to A[0].
Pass 2: 10 to 30 i eA[4] to A[1]
Pass 3 : 20 to 40 i.e A[3] to A[2]
Pass 4 : 30 to 40 A[4] to A[3]
Pass 5 : 40 to 50 no exchange

• The smallest element is found in first pass that is 9 and it is placed at the first position.
• In 40 pass, smallest element is searched from the rest of the element excluding first element.
• Selection sort keeps doing this, until the array is sorted.

Program for Selection Sort

#include <stdio.h> int main()


{
int array[100], n, c, d, position, swap;
printf("Enter number of elements\n");
scanf("%d", &n);
printf("Enter %d integers\n", n);
for ( c = 0 ; c < n ; c++ )
scanf("%d", &array[c]);
for ( c = 0 ; c < ( n - 1 ) ; c++ )
{
position = c;
for ( d = c + 1 ; d < n ; d++ )
{
if ( array[position] > array[d] )
position = d;
}
if ( position != c )
{
swap = array[c];
array[c] = array[position]; array[position] = swap;
}
}
printf("Sorted list in ascending order:\n"); for ( c = 0 ; c < n ; c++ ) printf("%d\n", array[c]); return 0;
}
Selection sort complexity

❑ Best Case Complexity - It occurs when there is no sorting required, i.e. the array is already
sorted. The best-case time complexity of selection sort is O(n2).
❑ Average Case Complexity - It occurs when the array elements are in jumbled order that is not
properly ascending and not properly descending. The average case time complexity of selection sort is
O(n2).
❑ Worst Case Complexity - It occurs when the array elements are required to be sorted in reverse order.
That means suppose you have to sort the array elements in ascending order, but its elements are in
I Sem BCA Data Structure Page 69
SJR College of Science, Arts and Commerce Dept. of Computer Science

descending order. The worst-case time complexity of selection sort is O(n2).

Algorithm

SELECTION SORT(arr, n)
Step 1: Repeat Steps 2 and 3 for i = 0 to n-1
Step 2: CALL SMALLEST(arr, i, n, pos)
Step 3: SWAP arr[i] with arr[pos]
Step 4 : temp= a[i]
a[i] = a[pos] a[pos] = temp [END OF LOOP]
Step 5: EXIT
(OR)

SMALLEST (arr, i, n, pos)


Step 1: [INITIALIZE] SET SMALL = arr[i]
Step 2: [INITIALIZE] SET pos = i
Step 3: Repeat for j = i+1 to n if (SMALL > arr[j])
SET SMALL = arr[j]
SET pos = j [END OF if] [END OF LOOP]
Step 4: RETURN pos

Write a program to implement selection sort in C language.

#include <stdio.h>
void selection(int arr[], int n)
{
int i, j, small;
for (i = 0; i < n-1; i++) // One by one move boundary of unsorted subarray
for (i = 0; i < n; i++) printf("%d ", a[i]);
}
int main()
{
int a[] = { 12, 31, 25, 8, 32, 17 };
int n = sizeof(a) / sizeof(a[0]);
printf("Before sorting array elements are - \n"); printArr(a, n); selection(a, n);
printf("\nAfter sorting array elements are - \n"); printArr(a, n); return 0;
}

4) Shell sort :

• shell sort is also Diminishing Increment Sort, it was developed by Donal L Shell .
• Shell sort is the generalization of insertion sort, which overcomes the drawbacks of insertion sort by

I Sem BCA Data Structure Page 70


SJR College of Science, Arts and Commerce Dept. of Computer Science

comparing elements separated by a gap/interval(increment value) of several positions.


• It is a sorting algorithm that is an extended version of insertion sort.
• Shell sort has improved the average time complexity of insertion sort. As similar to insertion sort, it is
a comparison-based and in- place sorting algorithm.
• Shell sort is efficient for medium-sized data sets.
• In insertion sort, at a time, elements can be moved ahead by one position only.
• To move an element to a far-away position, many movements are required that increase the
algorithm's execution time.
• But shell sort overcomes this drawback of insertion sort. It allows the movement and swapping
of far-away elements as well.
• This algorithm first sorts the elements that are far away from each other, then it subsequently
reduces the gap between them.
• This gap is called as interval. This interval can be calculated by using the Knuth's formula given
below
h=h*3+1
where, 'h' is the interval having initial value 1.

Algorithm

The simple steps of achieving the shell sort are listed as follows -

ShellSort(a, n) // 'a' is the given array, 'n' is the size of array


for (interval = n/2; interval > 0; interval /= 2)
for ( i = interval; i < n; i += 1) temp = a[i];
for (j = i; j >= interval && a[j - interval] > temp; j-= interval)
a[j] = a[j - interval];
a[j] = temp;
End ShellSort

Working of Shell sort Algorithm

Now, let's see the working of the shell sort Algorithm.

To understand the working of the shell sort algorithm, let's take an unsorted array. It will be easier to
understand the shell sort via an example.

Let the elements of array are -

Shell Sort Algorithm

We will use the original sequence of shell sort, i.e., N/2, N/4,.. .,1 as the intervals.

• In the first loop, n is equal to 8 (size of the array), so the elements are lying at the interval of 4 (n/2 = 4).

I Sem BCA Data Structure Page 71


SJR College of Science, Arts and Commerce Dept. of Computer Science

• Elements will be compared and swapped if they are not in order.


• Here, in the first loop, the element at the 0th position will be compared with the element at 4th position.
If the 0th element is greater, it will be swapped with the element at 4th position.
• Otherwise, it remains the same. This process will continue for the remaining elements.
• At the interval of 4, the sublists are {33, 12},{31, 17}, {40, 25}, {8, 42}.

Now, we have to compare the values in every sub-list.

After comparing, we have to swap them if required in the original array. After comparing and swapping, the

updated array will look as follows -

In the second loop, elements are lying at the interval of 2 (n/4 = 2), where n = 8. Now, we are taking the

interval of 2 to sort the rest of the array.

With an interval of 2, two sublists will be generated - {12, 25, 33, 40}, and {17, 8, 31, 42}.

Now, we again have to compare the values in every sub-list.

After comparing, we have to swap them if required in the original array. After comparing and swapping, the

updated array will look as follows -

In the third loop, elements are lying at the interval of 1 (n/8 = 1), where n = 8. At last, we use the interval of

value 1 to sort the rest of the array elements.


I Sem BCA Data Structure Page 72
SJR College of Science, Arts and Commerce Dept. of Computer Science

In this step, shell sort uses insertion sort to sort the array elements.

Shell sort complexity


Best Case Complexity - It occurs when there is no sorting required, i.e., the array is already sorted. The
best-case time complexity of Shell sort is O(n*logn).

Average Case Complexity - It occurs when the array elements are in jumbled order that is not
properly ascending and not properly descending. The average case time complexity of Shell sort is
O(n*logn).
Worst Case Complexity - It occurs when the array elements are required to be sorted in reverse order. That
means suppose you have to sort the array elements in ascending order, but its elements are in descending
order. The worst-case time complexity of Shell sort is O(n2).

Write a program to implement Shell sort in C language.


#include <stdio.h>
/* function to implement shellSort */ int shell(int a[], int n)
{
/* Rearrange the array elements at n/2, n/4, ..., 1 intervals */

for (int interval = n/2; interval > 0; interval /= 2)

{
for (int i = interval; i < n; i += 1)
{
/* store a[i] to the variable temp and make the ith position empty */

int temp = a[i]; int j;


for (j = i; j >= interval && a[j - interval] > temp; j -= interval) a[j] = a[j - interval];

// put temp (the original a[i]) in its correct position

a[j] = temp;

I Sem BCA Data Structure Page 73


SJR College of Science, Arts and Commerce Dept. of Computer Science

}
return 0;
}
void printArr(int a[], int n) /* function to print the array elements */

{
int i;
for (i = 0; i < n; i++) printf("%d ", a[i]);
}
int main()
{
int a[] = { 33, 31, 40, 8, 12, 17, 25, 42 };
int n = sizeof(a) / sizeof(a[0]);
printf("Before sorting array elements are - \n");
printArr(a, n); shell(a, n);
printf("\nAfter applying shell sort, the array elements are - \n");
printArr(a, n);
return 0;
}

I Sem BCA Data Structure Page 74


SJR College of Science, Arts and Commerce Dept. of Computer Science

Divide and Conquer Technique:

• In divide and conquer approach, the problem , is divided into smaller sub- problems and then each
problem is solved independently.
• When we keep on dividing the subproblems into even smaller sub- problems, we may eventually
reach a stage where no more division is possible.
• Those "atomic" smallest possible sub- problem (fractions) are solved.
• The solution of all sub-problems is finally merged in order to obtain the solution of an original
problem.

I Sem BCA Data Structure Page 75


SJR College of Science, Arts and Commerce Dept. of Computer Science

Divide and Conquer algorithm consists of the following three steps.


Divide :
Divide the original problem into a set of subproblems.
Conquer:
Solve every subproblem individually, recursively.If the sub- problem is small enough ,then solve the
sub problem.
Combine: Put together the solutions of the subproblems to get the solution to the whole problem.

Explaination Divide/Break:
• This step involves breaking the problem into smaller sub-problems.
• Sub-problems should represent a part of the original problem.
• This step generally takes a recursive approach to divide the problem until no sub-problem is further
divisible.
• At this stage, sub-problems become atomic in nature but still represent some part of the actual
problem.

Conquer/Solve:
• This step receives a lot of smaller sub- problems to be solved.
• Generally, at this level, the problems are considered 'solved' on their own.

Merge/Combine:
• When the smaller sub-problems are solved, this stage recursively combines them until they
formulate a solution of the original problem.
• This algorithmic approach works recursively and conquer & merge steps works so close that
they appear as one.
divide-and-conquer programming approach −

1. Merge Sort

2. Quick Sort

I Sem BCA Data Structure Page 76


SJR College of Science, Arts and Commerce Dept. of Computer Science

1) Merge Sort for Contiguous List(array):


✔ It is a sorting algorithm that sorts an array by making comparisons.
✔ It starts by dividing an array into sub- array and then recursively sorts each of them in ascending
order
✔ After the sorting is done, it merges them back to produce single sorted sequence of n element.
The technique performed are :
1. Divide the sequence of elements into two equal parts.

2. Recursively sort the elements of the left part. 1.Recursively sort the elements of the right part.

3. Merge the sorted left and right parts into a single sorted array.

4. We divided the array into two parts based on mid value i e mid = (low+ high)/2

Example : A= (36,25,40,2,7,80,15)

Step1:The merge sort algorithm iteratively divides an array into equal halves until we achieve an atomic
value.
In case if there are an odd number of elements in an array, then one of the halves will have more elements
than the other half.
Step2: After dividing an array into two subarrays, we will notice that it did not block the order of
elements as they were in the original array.
After now, we will further divide these two arrays into other halves.

Step3: Again, we will divide these arrays until we achieve an atomic value, i.e., a value that cannot be
further divided.
Step4: Next, we will merge them back in the same way as they were broken down.
Step5: For each list, we will first compare the element and then combine them to form a new sorted list.
Step6: In the next iteration, we will compare the lists of two data values and merge them back into a list
of found data values, all placed in a sorted manner.

I Sem BCA Data Structure Page 77


SJR College of Science, Arts and Commerce Dept. of Computer Science

Algorithm :
Step 1: if (low <high)
Step 2: mid =(low +high)/2
Step 3: call mergesort(A,low,mid)
Step 4: call mergesort(A,mid+1,high)
Step 5:call mergesort(A,low,mid,high)
Step 6: end if
Step 7: exit

I Sem BCA Data Structure Page 78


SJR College of Science, Arts and Commerce Dept. of Computer Science

I Sem BCA Data Structure Page 79


SJR College of Science, Arts and Commerce Dept. of Computer Science

I Sem BCA Data Structure Page 80


SJR College of Science, Arts and Commerce Dept. of Computer Science

Merge Sort Complexity :

Best Case Complexity: The merge sort algorithm has a best-case time complexity of O(n*log n) for the
already sorted array.

Average Case Complexity: The average-case time complexity for the merge sort algorithm is O(n*log n),
which happens when 2 or more elements are jumbled, i.e., neither in the ascending order nor in the
descending order.

Worst Case Complexity: The worst-case time complexity is also O(n*log n), which occurs when we sort
the descending order of an array into the ascending order.
Space Complexity: The space complexity of merge sort is O(n).

6) Quick Sort

Quick sort is also known as Partition-exchange sort based on the rule of Divide and Conquer.

Divide and conquer is a technique of breaking down the algorithms into subproblems, then solving
the subproblems, and combining the results back together to solve the original problem.

Divide:
□ In Divide, first pick a pivot element.
□ After that, partition or rearrange the array into two sub-arrays such that each element in the left sub-
array is less than or equal to the pivot element and each element in the right sub-array is larger than
the pivot element.
Conquer:

□ Recursively, sort two subarrays with Quicksort.


□ It is a highly efficient sorting algorithm.
□ Quick sort is the quickest comparison-based sorting algorithm.

□ It is very fast and requires less additional space, only O(n log n) space is required.

□ Quick sort picks an element as pivot and partitions the array around the picked pivot.

There are different versions of quick sort which choose the pivot in different ways:

1. First element as pivot

I Sem BCA Data Structure Page 81


SJR College of Science, Arts and Commerce Dept. of Computer Science

Last element as pivot

Random element as pivot

Median as pivot

Algorithm for Quick Sort

Step 1: Choose the highest index value as pivot.


Step 2: Take two variables to point left and right of the list excluding pivot.
Step 3: Left points to the low index.
Step 4: Right points to the high index.
Step 5: While value at left < (Less than) pivot move right. Step 6: While value at right > (Greater than) pivot
move left.
Step 7: If both Step 5 and Step 6 does not match, swap left and right.
Step 8: If left = (Less than or Equal to) right, the point where they met is new pivot.

I Sem BCA Data Structure Page 82


SJR College of Science, Arts and Commerce Dept. of Computer Science

❖ The above diagram represents how to find the pivot value in an array.
❖ As we see, pivot value divides the list into two parts (partitions) and then each part is processed
for quick sort.
❖ Quick sort is a recursive function. We can call the partition function again.

Program of quick sort


#include<stdio.h>
#include<conio.h>
//quick Sort function to Sort Integer array list
void quicksort(int array[], int firstIndex, int lastIndex)
{
//declaaring index variables
int pivotIndex, temp, index1, index2;
if(firstIndex < lastIndex)
{
//assigninh first element index as pivot element
pivotIndex = firstIndex;
index1 = firstIndex;
index2 = lastIndex;
//Sorting in Ascending order with quick sort while(index1 < index2)
{
while(array[index1] <= array[pivotIndex] && index1 < lastIndex)

{
index1++;
}
while(array[index2]>array[pivotIndex])
{
index2--;
}
if(index1<index2)
{
//Swapping opertation temp = array[index1];
array[index1] = array[index2];
array[index2] = temp;
}
}
//At the end of first iteration, swap pivot element with index2 element
temp = array[pivotIndex];
array[pivotIndex] = array[index2];
array[index2] = temp;
//Recursive call for quick sort, with partiontioning
quicksort(array, firstIndex, index2-1);
quicksort(array, index2+1, lastIndex);
}
}
I Sem BCA Data Structure Page 83
SJR College of Science, Arts and Commerce Dept. of Computer Science

int main()
{
//Declaring variables int array[100],n,i;
//Number of elements in array form user input
printf("Enter the number of element you want to Sort: ");
scanf("%d",&n);
//code to ask to enter elements from user equal to n
printf("Enter Elements in the list : ");
for(i = 0; i < n; i++)
{
scanf("%d",&array[i]);
}
//calling quickSort function defined above
quicksort(array,0,n-1);
//print sorted array
printf("Sorted elements: ");
for(i=0;i<n;i++)
printf(" %d",array[i]);
getch();
return 0;}
Quicksort complexity

❑ Best Case Complexity - In Quicksort, the best-case occurs when the pivot element is the middle
element or near to the middle element. The best-case time complexity of quicksort is O(n*logn).

❑ Average Case Complexity - It occurs when the array elements are in jumbled order that is not
properly ascending and not properly descending. The average case time complexity of quicksort is
O(n*logn).

❑ Worst Case Complexity - In quick sort, worst case occurs when the pivot element is either greatest or
smallest element. Suppose, if the pivot element is always the last element of the array, the worst case
would occur when the given array is sorted already in ascending or descending order. The worst-case
time complexity of quicksort is O(n2).

Write a program to implement quicksort in C language.

#include <stdio.h>
/* function that consider last element as pivot, place the pivot at its exact position, and place smaller
elements to left of pivot and greater elements to right of pivot. */
int partition (int a[], int start, int end)
{
int pivot = a[end]; // pivot element
int i = (start - 1);
for (int j = start; j <= end - 1; j++)
{
// If current element is smaller than the pivot
if (a[j] < pivot)
I Sem BCA Data Structure Page 84
SJR College of Science, Arts and Commerce Dept. of Computer Science

{
i++; // increment index of smaller element
int t = a[i];
a[i] = a[j];
a[j] = t;
}
}
int t = a[i+1];
a[i+1] = a[end];
a[end] = t;
return (i + 1);
}
/* function to implement quick sort */
void quick(int a[], int start, int end) /* a[] = array to be sorted, start = Starting index, end = Ending index */
{
if (start < end)
{
int p = partition(a, start, end); //p is the partitioning index
quick(a, start, p - 1);
quick(a, p + 1, end);
}}

/* function to print an array */

void printArr(int a[], int n)


{
int i;
for (i = 0; i < n; i++)
printf("%d ", a[i]);
}
int main()
{
int a[] = { 24, 9, 29, 14, 19, 27 };
int n = sizeof(a) / sizeof(a[0]);
printf("Before sorting array elements are - \n");
printArr(a, n);
quick(a, 0, n - 1);
printf("\nAfter sorting array elements are - \n");
printArr(a, n);
return 0;
}

5) Merge Sort Algorithm


❖ he merge sort Algorithm. Merge sort is the sorting technique that follows the divide and
conquer approach.

❖ Merge sort is similar to the quick sort algorithm as it uses the divide and conquer approach to sort
the elements.
I Sem BCA Data Structure Page 85
SJR College of Science, Arts and Commerce Dept. of Computer Science

❖ It is one of the most popular and efficient sorting algorithm.

❖ It divides the given list into two equal halves, calls itself for the two halves and then merges the
two sorted halves.

❖ We have to define the merge() function to perform the merging.

❖ The sub-lists are divided again and again into halves until the list cannot be divided further.

❖ Then we combine the pair of one element lists into two-element lists, sorting them in the process.

❖ The sorted two-element pairs is merged into the four-element lists, and so on until we get the sorted
list.

Algorithm
In the following algorithm, arr is the given array, beg is the starting element, and end is the last element of
the array.

MERGE_SORT(arr, beg, end)


if beg < end
set mid = (beg + end)/2
MERGE_SORT(arr, beg, mid)
MERGE_SORT(arr, mid + 1, end)
MERGE (arr, beg, mid, end)
end of if
END MERGE_SORT

The important part of the merge sort is the MERGE function. This function performs the merging of
two sorted sub-arrays that are A[beg…mid] and A[mid+1…end], to build one sorted array A[beg…end]. So,
the inputs of the MERGE function are A[], beg, mid, and end

implementation of the MERGE function is given as follows -

Function to merge the subarrays of a[] */ void merge(int a[], int beg, int mid, int end)
{
int i, j, k;
int n1 = mid - beg + 1;
int n2 = end - mid;
int LeftArray[n1], RightArray[n2]; //temporary arrays
/* copy data to temp arrays */
for (int i = 0; i < n1; i++)
LeftArray[i] = a[beg + i];
for (int j = 0; j < n2; j++)
RightArray[j] = a[mid + 1 + j];
i = 0, /* initial index of first sub-array */
j = 0; /* initial index of second sub-array */
k = beg; /* initial index of merged sub-array */
while (i < n1 && j < n2)
{

I Sem BCA Data Structure Page 86


SJR College of Science, Arts and Commerce Dept. of Computer Science

if(LeftArray[i] <= RightArray[j])


{
a[k] = LeftArray[i];
i++;
}
else
{
a[k] = RightArray[j];
j++;
}
k++;
}
while (i<n1)
{
a[k] = LeftArray[i];
i++;
k++;
}
while (j<n2)
{
a[k] = RightArray[j];
j++;
k++;
}
}
Working of Merge sort Algorithm

□ Now, let's see the working of merge sort Algorithm.

□ To understand the working of the merge sort algorithm, let's take an unsorted array.

□ It will be easier to understand the merge sort via an example.

Let the elements of array are -

According to the merge sort, first divide the given array into two equal halves. Merge sort keeps dividing
the list into equal parts until it cannot be further divided.

As there are eight elements in the given array, so it is divided into two arrays of size 4.

Now, again divide these two arrays into halves. As they are of size 4, so divide them into new arrays of size

I Sem BCA Data Structure Page 87


SJR College of Science, Arts and Commerce Dept. of Computer Science

2.

Now, again divide these arrays to get the atomic value that cannot be further divided.

● Now, combine them in the same manner they were broken.

● In combining, first compare the element of each array and then combine them into another array
in sorted order.

● So, first compare 12 and 31, both are in sorted positions.

● Then compare 25 and 8, and in the list of two values, put 8 first followed by 25.

● Then compare 32 and 17, sort them and put 17 first followed by 32. After that, compare 40
and 42, and place them sequentially.

● Now, there is a final merging of the arrays. After the final merging of above arrays, the array will
look like -

Write a program to implement merge sort in C language.

#include <stdio.h>
/* Function to merge the subarrays of a[] */
void merge(int a[], int beg, int mid, int end)
{
int i, j, k;
int n1 = mid - beg + 1;
int n2 = end - mid;
int LeftArray[n1], RightArray[n2]; //temporary arrays
/* copy data to temp arrays */
for (int i = 0; i < n1; i++)
LeftArray[i] = a[beg + i];
for (int j = 0; j < n2; j++)
RightArray[j] = a[mid + 1 + j];
i = 0; /* initial index of first sub-array */
j = 0; /* initial index of second sub-array */
k = beg; /* initial index of merged sub-array */

I Sem BCA Data Structure Page 88


SJR College of Science, Arts and Commerce Dept. of Computer Science

while (i < n1 && j < n2)


{
if(LeftArray[i] <= RightArray[j])
{
a[k] = LeftArray[i];
i++;
}
else
{
a[k] = RightArray[j];
j++;
}
k++;
}
while (i<n1)
{
a[k] = LeftArray[i];
i++;
k++;
}
while (j<n2)
{
a[k] = RightArray[j];
j++;
k++;
}
}

void mergeSort(int a[], int beg, int end)


{
if (beg < end)
{
int mid = (beg + end) / 2;
mergeSort(a, beg, mid);
mergeSort(a, mid + 1, end);
merge(a, beg, mid, end);
}
}
/* Function to print the array */
void printArray(int a[], int n)
{
int i;
for (i = 0; i < n; i++)
printf("%d ", a[i]);
printf("\n");
}
int main()
{
int a[] = { 12, 31, 25, 8, 32, 17, 40, 42 };

I Sem BCA Data Structure Page 89


SJR College of Science, Arts and Commerce Dept. of Computer Science

int n = sizeof(a) / sizeof(a[0]);


printf("Before sorting array elements are - \n");
printArray(a, n);
mergeSort(a, 0, n - 1);
printf("After sorting array elements are - \n");
printArray(a, n);
return 0;
}

I Sem BCA Data Structure Page 90


SJR College of Science, Arts and Commerce Dept. of Computer Science

Hashing
Hashing
Ø Hashing is one of the searching techniques that uses a constant time.
Ø The time complexity in hashing is O(1).
Ø hashing technique provides a constant time.
Ø In Hashing technique, the hash table and hash function are used.
Ø Using the hash function, we can calculate the address at which the value can be stored.
Ø The main idea behind the hashing is to create the (key/value) pairs.
Ø If the key is given, then the algorithm computes the index at which the value would be stored.
Ø It can be written as:
Index = hash(key)
Example :
In schools, the teacher assigns a unique roll number to each student. Later, the teacher uses that roll
number to retrieve information about that student.

Hash Table
Ø A Hash table is a data structure that stores some information, and the information has basically two
main components, i.e., key and value.
Ø The hash table can be implemented with the help of an array format for storing the data.
Ø It is used to access fast .
Ø Hashing uses this unique index to perform insert, update, and search operations.

Hash Function
Ø It is used to convert the key into the array index.
Ø It is denoted by H.
Ø Let key I'd denoted by k and hash function by h(k).

Characteristics
Ø Easy to compute
Ø Uniform Distribution
Ø Less collision
Ø High load factor : Load factor = number of elements in hash table /size.
Example:
Ø Let hash function be h(k)= k mod 10
Ø Where k is a key
Ø The key are 12,11,14,17,16,15,18,13
I Sem BCA Data Structure Page 91
SJR College of Science, Arts and Commerce Dept. of Computer Science

Ø First the hash table will be empty having the table size of 10 and index starting from 0
Ø To insert values into hash table we will use the hash function.
H(12)=12 mod 10=2 ,now the 12 will be inserted into 2nd index of an array.
H(11)=11 mod 10=1
H(14)=14 mod 10=4
H(17)=17 mod 10=7
H(16)=16 mod 10=6
H(15)=15 mod 10=5
H(18)=18 mod 10=8
H(13)=13 mod 10=3
Index Key
0
1 11
2 12
3 13
4 14
5 15
6 16
7 17
8 18
9

Hash Collision
Ø Collision is occured when two keys generate the same value.
Ø we ve to choose the good hash function,so that the has function doesn't generate the same index for
multiple key.
Example
Let keybe 12 and 42 and h(k) = k mod 10
H(12) = 12 mod 10 =2
H((42)= 42 mod 10 = 2
Here both the key generate the same index,but we can store only one of them,both collision is occured
is is called hash collision or hash clash.

To avoid the collision there are 2 ways


1) Choosing good hash function(minimum collision)
2) Resolving the collision

Choosing a hash function


Choosing good hash function(minimum collision)
1. Division Method
2. Midsquare Method
3. Folding Method
4. Mixed Method

I Sem BCA Data Structure Page 92


SJR College of Science, Arts and Commerce Dept. of Computer Science

Division Method
Ø It divides X by M and chossses it's remainder has an index position.
Ø H(x)=X mod M
Ø If M is even number then h(x)is also even and if mis odd number then h(x,) is also odd.
Ø We should take the M has Prime number for minimizing the collision.
Example
Ø ‘ a’ consist of address of 100 i.e 00-99 with two digits and consider the employee number of 4 digits
with unique value .
Ø i.e 1675,2432,5209
Ø Select a prime number for M that is near to 99 is 97
Ø H(1675)= 1675 mod 97= 26

Midsquare Method
Ø First square the key element and select some digits from the middle of that squaring number. Or
Ø Select the third and fourth digits from the right hand side of the squaring element and generate is has
hash address
Ø K= 1675
Ø K2 = 2805625 = h(k)= 56

Folding Method
Ø The key is broken into pieces and then add all of them to get the hash address.
Ø H(k)=1675=16+75= 91
Ø H(8677)= 86+77= 163=63
Ø We ignore the last carry, because that should have the same number of digits as the required address.
Ø Sometimes we reverse the some piece of elements into evening and then add to get the hash address
Ø H(k)=1675=16+57= 73

Mixed Method
Ø Here we mix up other methods with division method to get the address in the range of hash table.
Ø Consider 8 digits key 27862123
Ø By using folding method
Ø H(27862123)=27+8621+23=8671
Ø Use division method for getting the address
Ø H(8671)=8671 mid 97=38

Collision Resolution
Ø This occurs when hash function address of two different keys points to same location.
Ø There are two technique
Ø Open addressing
Ø Chaining

Open addressing
Ø It stores the value in the hash table.
Ø Hash table has two types of values
 Sentinel value (-1)
I Sem BCA Data Structure Page 93
SJR College of Science, Arts and Commerce Dept. of Computer Science

 Data-value
Sentinel value
 It indicates that the location contains no data value at present, but it can be used to the hold value in
it.
Ø The key is mapped to a particular memory location,then the value it holds is checked.
Ø If the location has some data values stored in it and other slots examined systematically in the forward
direction to find free slot.
Ø If we don't find any free location then it is overflow.
Ø The process of examining memory location in the Hash table is called probing.
Ø Open address can be implemented using :
• linear probing,
• quadratic probing ,
• double hashing, and
• rehashing.
ü Linear probing
• It generates address value through Hash Function and maps the key on particular position in Hash
table.
• If the key has same hash address then it will find next empty position in Hash table.
• The Hash table as a circular array format.
• If the table size is N after N-1, it will again search for zero position in array.
• Example
• Key -25,46,10,36,18,29,43 here the table size is 11
• It uses division method to store the value.
• 25 mod 11=3 ,so now the 25 is stored in 3rd position in the hash table and so on..
• 46 mod11= 2
• 10 mod 11=10
• 36 mod 11= 3, but it is already occupied by 25 so insert into next place that is 4th position.
• 43 mod 11= 10, but this is already occupied by the 10, so 43 will be inserted to the next free space
which is 0th position.
• For searching element feature the has generated address position in the table.
• If the element is not available at that position then check and sequentially search the element after the
hash address position i e a,a+1,a+2 so on..
• Insertion and Searching takes place is (a+i) where i =0,1,2,3.....
• Limitation : the record tends to cluster i.e when half of the table is full then it's difficult to find the
empty in hash table.

Quadratic Probing :
• To overcome the limitations of linear probing this method is used
• Here the insertion and searching takes place is (a+i2) at the location a+1,a+4,a+9......
• It reduces the cluster problem but it can't search all locations,it searches only when it table size is
prime number,i.e only half.
• It also used division method.
• Consider previous example, but add 47 to it.
• It uses 3rd position,but the 3rd and 4th position is occupied,so uses (a+4) i e (3+4)=7 it is also
occupied so (a+9) i e(3+9)=12 where 12%11=1.
I Sem BCA Data Structure Page 94
SJR College of Science, Arts and Commerce Dept. of Computer Science

Double hashing
 It requires the hashing second time in case of collision.
 The generated address of a hash function H is ‘a‘ when collision is occured again do the hashing for
this hash function.
 Let hash function is H1 and it's address is a1.
 Insert and search at the location a,a+a1,a+2a1,a+3a1.
 Two time the calculation of hash function which creates it complex and search will be slower .
 Example :
 Consider the table size as 11 and 2 hash function bisb
 General division method : H(k)=k % 11 and
 H1(k)=9 - (k % 9) and then apply a,a+a1,a+2a1,a+3a1.
 Elements are 25,46,10,36,18,29
 By using division method
 H(25)=25%11=3 ,46 in 2nd,10 in 10 th,
 36 % 11=3,but already exists
 H1(36) = 9 - 36 % 9= 9-0=9
 a+a1= 3 + 9= 12= 12% 11 =1
 18 is at 7, 29 is at 7 but it's already exists,so H1= 9 - 29 %9 = 9-2= 7
 a+a1= 7 + 7= 14%11= 3 not free
 a+2a1 = 7+14= 21%11 10 not free
 a+3a1= 7+21= 28%11= 6 free so insert
Rehashing
 When hash table is full insertion is not possible.
 The solution is to create a new hash function and insert all element of the previous had tableb.
 Scan the element of the previous hash table one by one and calculate the hash keybwith hash function
and insert into new hash table.
 Double the size of your hash table i.e11 (is 22)and chose the nearest Prime number 23
 Now create a new hash table with the size of 23.
 Once the new table is created again start the division method for the given key.
Example :
 54mod 11=10
 54 mod 23=8
 43 mod 23= 20
 0  43
 1 
 2
 46
 3  25
 4
 4  36
 5 
 6

I Sem BCA Data Structure Page 95


SJR College of Science, Arts and Commerce Dept. of Computer Science

 7
 18

 8
 29

 9

 10
 10

I Sem BCA Data Structure Page 96

You might also like