Sample Lab Report
Analysis and Design of Algorithm (CSE 303)
B.Tech. CSE, 5th Semester
Amity University Kolkata
Experiment No 1:
Aim: Program of insertion sort implementation using array in ascending order
in C programming language. Analyse the code for Time and Space Complexity.
Algorithm:
C Program:
#include <stdio.h>
void main()
{
int List[100];
int size;
int i, j, temp, count=1;
printf ("\n Enter the size of the list");
scanf ("%d", &size);
printf ("\n Enter the list one by one");
for (i = 1; i <=size; i++)
{
scanf ("%d", &List[i]);
}
/* Sort the list by Insertion sort */
for (i=1; i<=size; i++)
{
count++;
temp = List[i]; /* Pick and save the first element of the n unsorted part*/
j= i - 1;
while ((temp < List[j])&& (j>=0)) /* Scan for proper place */
{
count++;
List[j + 1] = List[j];
j = j - 1;
count++;
}
List[j+1] = temp; /* Insert the element at the proper place */
}
printf ("The number of steps is= %d\n", count);
/* Print the sorted list*/
printf ("\n The sorted list is ....");
for (i = 1; i<=size; i++)
{
printf ("%d\n", List[i]);
}
}
Outputs for various input size (various values of n):
Plots for 3 Cases:
Example Case 1 (Worst Case):
Theoretical Graph Obtained Graph
Case 2 (Average Case):
<two graphs>
Case 3 (Best Case):
<two graphs>
Observations:
Time Complexity: Worst case:O(n2)
Average case: ϴ(n2 )
Best Case: Ω(n)
Auxiliary Space: O(1) (constant space required)
Boundary Cases: Insertion sort takes maximum time to sort if elements are
sorted in reverse order. And it takes minimum time (Order of n) when elements
are already sorted.
Algorithmic Paradigm: Incremental Approach
Sorting In Place: Yes
Stable: Yes
Uses: Insertion sort is uses when number of elements is small. It can also be
useful when input array is almost sorted, only few elements are misplaced in
complete big array.
Conclusion: Hence, the analysis of insertion sort in worst, best and average
case is found to be correct.