0% found this document useful (0 votes)
15 views31 pages

DS Unit 1

Uploaded by

resoce3697
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views31 pages

DS Unit 1

Uploaded by

resoce3697
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

DATA STRUCTURES

UNIT – I

DATA STRUCTURES
DEFINITION
A data structure is a group of data elements that are put together
under one name and which defines a particular way of storing and
organizing data in a computer so that it can be used efficiently.
or
It is the way of organizing, storing, retrieving data and maintaining
their relationship with each other.
or
It is the logical and mathematical model to organize and store
data in computer memory so that we can use it efficiently.

Characteristics of Data Structures


✓ It represents the logical representation of data in computer memory.
✓ It represents the logical relationship between the various data
elements.
✓ It helps in efficient manipulation of stored data elements.
✓ It allows the programs to process the data in an efficient manner.

Applications of Data Structures


Data structures are widely applied in the following areas:
✓ Compiler design
✓ Operating system
✓ Statistical analysis package
✓ DBMS
✓ Numerical analysis
✓ Simulation
✓ Artificial intelligence
✓ Graphics

1
Dr. Ratna Raju Mukiri M.Tech(CSE)., S.E.T., Ph.D., PDF.,
DEPARTMENT OF CSE, SACET, CHIRALA
DATA STRUCTURES

IMPORTANCE OF LINEAR DATA STRUCTURES


The data structures have been classified into two types:
✓ Primitive Data Structures
✓ Non – Primitive Data Structures
Primitive Data Structures
✓ It is also known as primary data structures.
✓ Primitive data structures are the fundamental data types which are
supported by a programming language.
✓ They can be directly manipulated by machine instructions.
✓ For example integer, real, character, and boolean.
Non – Primitive Data Structures
✓ It is also known as secondary data structures.
✓ They are created by using primitive data structures.
✓ Its main objective is to form a set of homogeneous or heterogeneous
data elements.
✓ For example linked lists, stacks, trees, and graphs.
✓ They are classified into two types:
✓ Linear data structures
✓ Non – Linear data structures

Linear Data Structure


✓ A data structure is said to linear data structure if all the data
elements are arranged in some linear or sequential order.
2
Dr. Ratna Raju Mukiri M.Tech(CSE)., S.E.T., Ph.D., PDF.,
DEPARTMENT OF CSE, SACET, CHIRALA
DATA STRUCTURES

✓ Examples for linear data structure are:


✓ Arrays
✓ Stacks
✓ Queues
✓ Linked Lists, etc.
✓ They can represented in memory in two ways:
✓ Using sequential memory locations
✓ Using links

1. ARRAYS
Arrays are classified into two types. They are single dimensional
arrays and multi-dimensional arrays.
Single Dimensional Arrays
“An array is defined as collection of elements that share a
common name”
✓ A list of items specified under one variable name using only one
subscript is called a single-subscripted variable
✓ It is known as one-dimensional array or 1D array
✓ It is also called as Single dimensional array.
✓ It is simply called as array.
✓ The subscript begins with the number 0.
Declaration of one dimensional Array
✓ An array variable is declared by specifying first the base type of the
array, then the name of the array variable, and then the number of
elements of the array that is specified between a pair square brackets
([]).
✓ The general format of array declaration is
type array_name[size];
✓ Ex:
int marks [100];
✓ Here int specifies the data type and marks specifies the name of the
array and size specifies the maximum size of the array.

3
Dr. Ratna Raju Mukiri M.Tech(CSE)., S.E.T., Ph.D., PDF.,
DEPARTMENT OF CSE, SACET, CHIRALA
DATA STRUCTURES

✓ From the above example the maximum size of the array is 100.
Multi-Dimensional Arrays
✓ If an array contains more than one dimension it is called multi-
dimensional array.
✓ If an array contains only two dimensions then it is called two
dimensional arrays.
✓ This two dimensional array is also called as matrix.
✓ It is called as array of arrays.
✓ Since it contains two subscripts it is also known as double
subscripted variable.
✓ It is used to represent table of values containing row values and
column values.

Two dimensional Array Declaration


✓ The two-dimensional array can be declared by specifying first the base
type of the array, then the name of the array variable, and then the
number of rows and column elements the array should be specified
between a pair square brackets ([] []).
✓ The general syntax is
type array_name[row size][column size];
✓ Ex:
int student[4][3];
✓ Here int specifies the data type and student specifies the name of the
array and size specifies the row size and column size of the array.
✓ From the above example there are 4 rows and 3 columns for the array
student.

2. Stacks
✓ A stack is a data structure in which addition of new element or
deletion of an existing element always takes place at the same end.
This end is known as top of stack.

4
Dr. Ratna Raju Mukiri M.Tech(CSE)., S.E.T., Ph.D., PDF.,
DEPARTMENT OF CSE, SACET, CHIRALA
DATA STRUCTURES

✓ When an item is added to a stack, the operation is called push, and


when an item is removed from the stack the operation is called pop.
✓ Stack is also called as Last-In-First-Out (LIFO) list. The element that
is inserted last is the first element to be removed from the stack.

Operations performed on Stacks


✓ There are three possible operations performed on a stack. They are
push, pop and peek.
✓ Push: Allows adding an element at the top of the stack.
✓ Pop: Allows removing an element from the top of the
stack.
✓ Peek: it returns the value of topmost element of the stack

3. Queues
✓ Queue is a linear data structure that permits insertion of new
element at one end and deletion of an element at the other end.
✓ The end at which the deletion of an element take place is called
front, and the end at which insertion of a new element can take place
is called rear.
✓ The deletion or insertion of elements can take place only at the front
or rear end called dequeue and enqueue.
✓ The first element that gets added into the queue is the first one to get
removed from the queue.
✓ The queue is referred to as First-In-First-Out list (FIFO).

5
Dr. Ratna Raju Mukiri M.Tech(CSE)., S.E.T., Ph.D., PDF.,
DEPARTMENT OF CSE, SACET, CHIRALA
DATA STRUCTURES

Operations Performed on Queues


There are two possible operations performed on a queue. They are
enqueue and dequeue.
✓ enqueue: Allows inserting an element at the rear of the queue.
✓ dequeue: Allows removing an element from the front of the queue.

4. Lists
✓ It is a collection of linear list of data elements. The data elements are
called nodes.
✓ Each node contains two parts: data and link. The data represents
integers and link is a pointer that points to next node.
✓ The last node of the linked list is not connected to any node so it
stores the value NULL in link part. Here NULL is defined as -1. NULL
pointer denotes end of the list.
✓ It contains pointer variable called start node that contains the address
of first node in the list. We can traverse the list starting from start
node that contains first node address and in turn first node contains
second node address and so on thus forming chain of nodes.
✓ If start == NULL then the list is empty.
✓ The diagrammatic representation of linked list is shown below:

6
Dr. Ratna Raju Mukiri M.Tech(CSE)., S.E.T., Ph.D., PDF.,
DEPARTMENT OF CSE, SACET, CHIRALA
DATA STRUCTURES

OPERATIONS ON DATA STRUCTURES


✓ The basic operations that can be performed on a data structure are:
✓ Insertion
✓ Deletion
✓ Search
✓ Traverse
✓ Sorting
✓ Merging

✓ Insertion: - It is used to add new data items to the given list of data
items. For example, to add the details of a new student who has
recently joined the course.
✓ Deletion: - It means to remove (delete) a particular data item from the
given collection of data items. For example, to delete the name of a
student who has left the course.
✓ Searching: - It is used to find the location of one or more data items
that satisfy the given constraint. Such a data item may or may not be
present in the given collection of data items. For example, to find the
names of all the students who secured 100 marks in mathematics.
✓ Traversing: - It means to access each data item exactly once so that it
can be processed. For example, to print the names of all the students
in a class.
✓ Sorting: - Data items can be arranged in some order like ascending
order or descending order. For example, arranging the names of
students in a class in an alphabetical order.
✓ Merging: - Lists of two sorted data items can be combined to form a
single list of sorted data items.

ABSTRACT DATA TYPE (ADT) AND THEIR IMPLEMENTATION


It is the logical description of how we can view the data and
operations that are allowed without implementation.
or

7
Dr. Ratna Raju Mukiri M.Tech(CSE)., S.E.T., Ph.D., PDF.,
DEPARTMENT OF CSE, SACET, CHIRALA
DATA STRUCTURES

It is defined as mathematical model representing data and


operations only but no implementation.
or
It is defined as a collections various data items and its operations
while hiding implementation.
or
It is defined as collection of instances and operations rather than
implementation.
or
It is defined as data together with functions that operate on that
data

Benefits / Advantages of ADT


✓ Modularity
✓ Reuse
✓ Code is easier to understand
✓ Implementation of ADT can be changed without requiring changes to
the program that uses ADT.

OVERVIEW OF TIME AND SPACE COMPLEXITY ANALYSIS


FOR LINEAR DATA STRUCTURES
✓ The performance of algorithm can be measured in terms of:
✓ Time
✓ Space
✓ The performance is the amount of memory needed and time required
to run it.
✓ We have two methods to determine the performance of the program.
✓ Analytical – in analysis
✓ Experimental – in measurement
✓ Time Complexity: The time complexity of an algorithm or a program
is the running time of the program as a function of input size.

8
Dr. Ratna Raju Mukiri M.Tech(CSE)., S.E.T., Ph.D., PDF.,
DEPARTMENT OF CSE, SACET, CHIRALA
DATA STRUCTURES

✓ Space Complexity: The space complexity of an algorithm or program


is the amount of computer memory required for program execution as
a function of input size.

Analysis of Algorithms
✓ It is a technique to compare efficiency of different algorithms
✓ The speed of an algorithm can be different on different computers(time
taken will be different)
✓ For solving a problem, the time is expressed in terms of
mathematical function of input size.
✓ Two algorithms are compared based on rate of growth of that
function
✓ If rate of growth is higher then the algorithm takes more time as
input size increases.
✓ The mathematical functions are represented by using asymptotic
notations
✓ It depends on how the program works efficiently.
✓ Efficiency means less space and less time required for execution.
✓ Hence time and space are the factors that determine the efficiency of
the program.
✓ We cannot compute time in terms of seconds for the execution of the
program because of several factors.
✓ Therefore we consider frequency count as time taken for execution of
the program.
✓ The frequency count is defined as the total number of times each
statement is being executed.

9
Dr. Ratna Raju Mukiri M.Tech(CSE)., S.E.T., Ph.D., PDF.,
DEPARTMENT OF CSE, SACET, CHIRALA
DATA STRUCTURES

10
Dr. Ratna Raju Mukiri M.Tech(CSE)., S.E.T., Ph.D., PDF.,
DEPARTMENT OF CSE, SACET, CHIRALA
DATA STRUCTURES

The time and space complexities of linear data structures are shown
below:

1. Arrays – the time complexity in array of size N is


✓ To access an element at specific memory address is O(1)
✓ Manipulation / Editing the element is O(1)
✓ To insert an element at specific index is O(N)
✓ To delete and element at specific index is O(N)
✓ The search operation also takes O(N)
The space complexity for array for insertion, deletion, fetching and
overwriting is O(1) since it does not require additional space.

2. Stacks - the time complexity of stack with N elements is


✓ To access an element in the stack is O(N)
✓ To insert an element into the stack O(1)
✓ To delete and element from the stack is O(1)
✓ The search operation for stack is O(N)
The space complexity for stack to perform any operation like insertion,
deletion, fetching and overwriting is O(1) since it does not require additional
space.
3. Queues - the time complexity of queue with N elements is
✓ To access an element in the queue is O(N)
✓ To insert an element into the queue O(1)
✓ To delete and element from the queue is O(1)
✓ The search operation for queue is O(N)
The space complexity for queue to perform any operation like
insertion, deletion, fetching and overwriting is O(1) since it does not require
additional space.
4. Lists - the time complexity of a list with N elements is
✓ To access an element in the list is O(N)
✓ To insert an element into the queue O(N) but insertion on start node is
O(1)
✓ To delete and element from the queue is O(N) but deletion on start
node is O(1)
11
Dr. Ratna Raju Mukiri M.Tech(CSE)., S.E.T., Ph.D., PDF.,
DEPARTMENT OF CSE, SACET, CHIRALA
DATA STRUCTURES

✓ The search operation for list is O(N)


The space complexity for list to perform any operation like insertion,
deletion, fetching and accessing is O(1) since it does not require additional
space.

SEARCHING
DEFINITION
It is a method of finding the given element is present in the given
list of elements or not.
or
It is technique to find the location where the element is available
or present in the list of elements.

Types of Searching
✓ Linear Search
✓ Binary Search
✓ Fibonacci Search

LINEAR SEARCH
✓ It is a very simple search algorithm when compared with the other
two search algorithms.
✓ It is also called as sequential search or indexed search.
✓ To perform linear search, the list of elements need not be sorted.
✓ An ordered or unordered list will be searched by comparing the search
element with one by one element from the beginning of the list until
the desired element is found or till the end of the list.
✓ If the desired element is found in the list then the search is successful
otherwise unsuccessful.
✓ The time complexity for linear search is O(n) where n is the number
of elements in the list.
✓ The time complexity increases with the increase of the input size n.

12
Dr. Ratna Raju Mukiri M.Tech(CSE)., S.E.T., Ph.D., PDF.,
DEPARTMENT OF CSE, SACET, CHIRALA
DATA STRUCTURES

Algorithm for Linear Search


LINEAR_SEARCH(A, N, KEY)
Step 1: SET POS = -1
Step 2: SET I = 0
Step 3: Repeat Step 4 while I<N
Step 4: IF KEY == A[I]
SET POS = I
PRINT POS
Go to Step 6
SET I = I + 1
Step 5: IF POS = –1
PRINT “VALUE IS NOT PRESENT IN THE ARRAY”
Step 6: EXIT

Example of Linear Search

13
Dr. Ratna Raju Mukiri M.Tech(CSE)., S.E.T., Ph.D., PDF.,
DEPARTMENT OF CSE, SACET, CHIRALA
DATA STRUCTURES

Program for Linear Search


#include<stdio.h>
int main(void)
{
int a[20], n, i, key;
printf("Enter size of the list: ");
scanf("%d", &n);
printf("Enter the elements”);
for(i = 0; i < n; i++)

14
Dr. Ratna Raju Mukiri M.Tech(CSE)., S.E.T., Ph.D., PDF.,
DEPARTMENT OF CSE, SACET, CHIRALA
DATA STRUCTURES

scanf("%d", &a[i]);
printf("Enter the element to be Search: ");
scanf("%d", &key);
for(i = 0; i < n; i++)
{
if(key == a[i])
{
printf("Element is found at %d index", i);
break;
}
}
if(i == n)
printf("Given element is not found in the li st!!!");
return 0;
}

BINARY SEARCH
✓ It is the fastest searching algorithm when compared with the other
two algorithms.
✓ It works on the principle divide – conquer strategy.
✓ To apply binary search algorithm the list of elements should be in
sorted order.
✓ The time complexity for binary search algorithm is O(log n).
✓ It is applied to very large set of elements
✓ The process carried by binary search algorithm is find the middle
element and compare it with search element it match return the
index of the element and say success otherwise see if the search
element is greater than or less than the middle element.
✓ If it is greater than the middle element then search the element in the
upper part of the list otherwise in the lower part of the list.
✓ Again find middle element and do the same process till the element is
found or not found.

15
Dr. Ratna Raju Mukiri M.Tech(CSE)., S.E.T., Ph.D., PDF.,
DEPARTMENT OF CSE, SACET, CHIRALA
DATA STRUCTURES

✓ Using binary search algorithm we can reduce the number of


comparisons hence it is best.

Algorithm for Binary Search


BINARY_SEARCH(A, lower_bound, upper_bound, KEY)
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 A[MID] == KEY
SET POS = MID
PRINT POS
Go to Step 6
ELSE IF A[MID] > VAL
SET END = MID - 1
ELSE
SET BEG = MID + 1
Step 5: IF POS = -1
PRINT “VALUE IS NOT PRESENT IN THE ARRAY”
Step 6: EXIT
Example of Binary Search

16
Dr. Ratna Raju Mukiri M.Tech(CSE)., S.E.T., Ph.D., PDF.,
DEPARTMENT OF CSE, SACET, CHIRALA
DATA STRUCTURES

17
Dr. Ratna Raju Mukiri M.Tech(CSE)., S.E.T., Ph.D., PDF.,
DEPARTMENT OF CSE, SACET, CHIRALA
DATA STRUCTURES

Program for Binary Search


#include <stdio.h>
int main(void)
{
int i, low, high, middle, n, key, a[10];
printf("Enter number of elements");
scanf("%d", &n);
printf("Enter the elements”);
for (i = 0; i < n; i++)
scanf("%d", &a[i]);
printf("Enter value to find");
scanf("%d", &key);
low = 0;
high = n - 1;
middle = (low + high)/2;
while(low <= high)
{
if(a[middle] < key)
low = middle + 1;
else if(a[middle] == key)
{
printf(“Element is found”);
break;
}
else
high = middle - 1;
middle = (low + high)/2;
}
if(low > high)
printf(“Element is not found” );
return 0;
}
18
Dr. Ratna Raju Mukiri M.Tech(CSE)., S.E.T., Ph.D., PDF.,
DEPARTMENT OF CSE, SACET, CHIRALA
DATA STRUCTURES

SORTING
DEFINITION
Sorting is a technique to rearrange the list of elements either in
ascending or descending order, which can be numerical, alphabetical or
any user-defined order.

Types of Sorting
Internal Sorting
✓ If the data to be sorted remains in main memory and also the sorting
is carried out in main memory then it is called internal sorting.
✓ Internal sorting takes place in the main memory of a computer.
✓ The internal sorting methods are applied to small collection of data.
✓ The following are some internal sorting techniques:
✓ Insertion sort
✓ Merge Sort
✓ Quick Sort
✓ Heap Sort

External Sorting
✓ If the data resides in secondary memory and is brought into main
memory in blocks for sorting and then result is returned back to
secondary memory is called external sorting.
✓ External sorting is required when the data being sorted do not fit into
the main memory.
✓ The following are some external sorting techniques:
✓ Two-Way External Merge Sort
✓ K-way External Merge Sort

19
Dr. Ratna Raju Mukiri M.Tech(CSE)., S.E.T., Ph.D., PDF.,
DEPARTMENT OF CSE, SACET, CHIRALA
DATA STRUCTURES

BUBBLE SORT
✓ It is known as exchange sort
✓ It is also known as comparison sort
✓ It is easiest and simple sort technique but inefficient.
✓ It is not a stable sorting technique.
✓ The time complexity of bubble sort is O(n2) in all cases.
✓ Bubble sort uses the concept of passes.
✓ The phases in which the elements are moving to acquire their proper
positions is called passes.
✓ It works by comparing adjacent elements and bubbles the largest
element towards right at the end of the first pass.
✓ The largest element gets sorted and placed at the end of the sorted
list.
✓ This process is repeated for all pairs of elements until it moves the
largest element to the end of the list in that iteration.
✓ Bubble sort consists of (n-1) passes, where n is the number of
elements to be sorted.
✓ In 1st pass the largest element will be placed in the nth position.
✓ In 2nd pass the second largest element will be placed in the (n-1)th
position.
✓ In (n-1)th pass only the first two elements are compared.

Algorithm for Bubble Sort


BUBBLE_SORT(A, N)
Step 1: Repeat Step 2 For I = 0 to N-1
Step 2: Repeat step 2 For J = 0 to N - I
Step 3: IF A[J] > A[J + 1]
SWAP A[J] and A[J+1]
Step 4: EXIT

20
Dr. Ratna Raju Mukiri M.Tech(CSE)., S.E.T., Ph.D., PDF.,
DEPARTMENT OF CSE, SACET, CHIRALA
DATA STRUCTURES

Example for Bubble Sort

21
Dr. Ratna Raju Mukiri M.Tech(CSE)., S.E.T., Ph.D., PDF.,
DEPARTMENT OF CSE, SACET, CHIRALA
DATA STRUCTURES

22
Dr. Ratna Raju Mukiri M.Tech(CSE)., S.E.T., Ph.D., PDF.,
DEPARTMENT OF CSE, SACET, CHIRALA
DATA STRUCTURES

Program for Bubble Sort


#include<stdio.h>
#include<conio.h>
int main(void)
{
int n, a[10], i, j , temp;
clrscr();
printf(" Enter the size of the array ");
scanf("%d", &n);
printf(" Enter the elements of the array ");
for(i=0; i<n; i++)
scanf("%d", &a[i]);
for(i=0; i<n-1; i++)
{
for(j=0; j<n; j++)
{
if(a[j] > a[j+1])
{
temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
}
printf(" The sorted list of elements are ");
for(i=0; i<n; i++)
printf("%d\t", a[i]);
return 0;
}

23
Dr. Ratna Raju Mukiri M.Tech(CSE)., S.E.T., Ph.D., PDF.,
DEPARTMENT OF CSE, SACET, CHIRALA
DATA STRUCTURES

SELECTION SORT
✓ It is easy and simple to implement
✓ It is used for small list of elements
✓ It uses less memory
✓ It is efficient than bubble sort technique
✓ It is not efficient when used with large list of elements
✓ It is not efficient than insertion sort technique when used with
large list
✓ The time complexity of selection sort is O(n2)
✓ Consider an array A with N elements. First find the smallest element
in the array and place it in the first position. Then, find the second
smallest element in the array and place it in the second position.
Repeat this procedure until the entire array is sorted.
✓ In Pass 1, find the position POS of the smallest element in the array
and then swap A[POS] and A[0]. Thus, A[0] is sorted.
✓ In Pass 2, find the position POS of the smallest element in sub-array
of N–1 elements. Swap A[POS] with A[1]. Now, A[0] and A[1] is
sorted.
✓ In Pass N–1, find the position POS of the smaller of the elements A[N–
2] and A[N–1]. Swap A[POS] and A[N–2] so that A[0], A[1], ..., A[N–1]
is sorted.

Algorithm for Selection Sort


SELECTION SORT(A, N)
Step 1: Repeat Steps 2 and 3 for I = 1 to N
Step 2: Call SMALLEST(A, I, N, pos)
Step 3: Swap A[I] with A[pos]
Step 4: Exit

SMALLEST (A, I, N, pos)


Step 1: SET small = A[I]
Step 2: SET POS = I

24
Dr. Ratna Raju Mukiri M.Tech(CSE)., S.E.T., Ph.D., PDF.,
DEPARTMENT OF CSE, SACET, CHIRALA
DATA STRUCTURES

Step 3: Repeat for J = I+1 to N


If small> A[J]
SET small = A[J]
SET pos = J
Step 4: Return pos
Step 5: Stop

Example for Selection Sort

25
Dr. Ratna Raju Mukiri M.Tech(CSE)., S.E.T., Ph.D., PDF.,
DEPARTMENT OF CSE, SACET, CHIRALA
DATA STRUCTURES

Program for Selection Sort


#include<stdio.h>
#include<conio.h>
int main(void)
{
int a[10], n, i, j, temp, minindex;
printf( "Enter the number of elements: " );
scanf("%d", &n);
printf( "\nEnter the elements:\n" );
for(i=0; i < n; i++)
scanf( "%d", &a[i] );
for( i=0; i < n; i++ )
{
minindex = i;
for( j=i+1; j <n; j++ )
{
if( a[j] < a[minindex] )
minindex = j;
}
temp = a[i];
a[i] = a[minindex];
a[minindex] = temp;
}
printf( "\nThe elements after sorting are: " );
for( i=0; i< n; i++ )
printf( "%d\t ", a[i] );
return 0;
}

26
Dr. Ratna Raju Mukiri M.Tech(CSE)., S.E.T., Ph.D., PDF.,
DEPARTMENT OF CSE, SACET, CHIRALA
DATA STRUCTURES

INSERTION SORT
In this method, the elements are inserted at their appropriate place.
Hence the name insertion sort.
✓ This sorting is very simple to implement.
✓ This method is very efficient when we want to sort small number of
elements.
✓ This method has excellent performance when almost the elements
are sorted.
✓ It is more efficient than bubble and selection sorts.
✓ This sorting is stable.
✓ This is an in-place sorting technique.
✓ The time complexity of insertion sort for best case is O(n), average

case and worst case is O(n2).

Algorithm for Insertion Sort


INSERTION-SORT (A, N)
Step 1: Repeat Steps 2 to 5 for I = 1 to N – 1
Step 2: SET TEMP = A[I]
Step 3: SET J = I - 1
Step 4: Repeat while J > = 0 and A[J] > TEMP
SET A[J + 1] = A[J]
SET J = J - 1
Step 5: SET A[J + 1] = TEMP
Step 6: EXIT
Example for insertion sort
Let us consider the array of elements to sort them using insertion sort
technique
30, 20, 10, 40, 50

27
Dr. Ratna Raju Mukiri M.Tech(CSE)., S.E.T., Ph.D., PDF.,
DEPARTMENT OF CSE, SACET, CHIRALA
DATA STRUCTURES

The control moves to while loop as j>=0 and a[j] > temp is true, the
while is executed.

Now since j >= 0 is false, control comes out of while loop

then the list becomes

The control moves to while loop as j>=0 and a[j] > temp is true, the
while is executed.

28
Dr. Ratna Raju Mukiri M.Tech(CSE)., S.E.T., Ph.D., PDF.,
DEPARTMENT OF CSE, SACET, CHIRALA
DATA STRUCTURES

Now since j >= 0 is false, control comes out of while loop

Then the list becomes

The control moves to while loop as j>=0 and a[j] > temp is false, the
while is not executed.

29
Dr. Ratna Raju Mukiri M.Tech(CSE)., S.E.T., Ph.D., PDF.,
DEPARTMENT OF CSE, SACET, CHIRALA
DATA STRUCTURES

Then the list becomes

The control moves to while loop as j>=0 and a[j] > temp is false, the
while is not executed.

Then the list becomes

Program for insertion sort


#include<stdio.h>
#include<conio.h>
int main(void)
{
int n, a[10], i, ,j, temp ;
clrscr();
printf(" Enter the size of the array ");
scanf("%d", &n);
30
Dr. Ratna Raju Mukiri M.Tech(CSE)., S.E.T., Ph.D., PDF.,
DEPARTMENT OF CSE, SACET, CHIRALA
DATA STRUCTURES

printf(" Enter the elements of the array ");


for(i=0; i<n; i++)
scanf("%d", &a[i]);
for(i=1; i<n; i++)
{
temp = a[i];
j = i - 1;
while(j >= 0 && a[j] > temp)
{
a[j+1] = a[j];
j = j - 1;
}
a[j+1]=temp;
}
printf(" \n The sorted list of elements are ");
for(i=0; i<n; i++)
printf("%d\t", a[i]);
return 0;
}

31
Dr. Ratna Raju Mukiri M.Tech(CSE)., S.E.T., Ph.D., PDF.,
DEPARTMENT OF CSE, SACET, CHIRALA

You might also like

pFad - Phonifier reborn

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

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


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy