Algo Assignment-04 Insertion Sort
Algo Assignment-04 Insertion Sort
Algo Assignment-04 Insertion Sort
GROUP-B
(Sorting: Quadratic & logarithmic time complexities)
Assign- 1) Implement Insertion Sort (The program should report the number of
pass & comparisons)
PROCEDURE
Insertion sort is a simple sorting algorithm that works by building a sorted array
one element at a time. It is considered an “in-place” sorting algorithm, meaning it
doesn’t require any additional memory space beyond the original array.
To achieve insertion sort, follow these steps:
• We have to start with second element of the array as first element in the
array is assumed to be sorted.
• Compare second element with the first element and check if the second
element is smaller then swap them.
• Move to the third element and compare it with the second element, then
the first element and swap as necessary to put it in the correct position
among the first three elements.
• Continue this process, comparing each element with the ones before it and
swapping as needed to place it in the correct position among the sorted
elements.
• Repeat until the entire array is sorted.
Algorithm
Step 1 − If it is the first element, it is already sorted. return 1;
Step 2 − Pick next element
Step 3 − Compare with all elements in the sorted sub-list
Step 4 − Shift all the elements in the sorted sub-list that is greater than the
value to be sorted
Step 5 − Insert the value
Step 6 − Repeat until list is sorted
Pseudocode
Insertion-Sort(A)
for j = 2 to A.length
key = A[j]
i=j–1
while i > 0 and A[i] > key
A[i + 1] = A[i]
i = i -1
A[i + 1] = key
/* Insertion Sort */
#include<stdio.h>
#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
void main()
{
clrscr();
FILE *in;
int n, i, Item, a[100];
cout<<"Enter Sample Size (No of Elements):";
cin>>n;
in=fopen("Algo\\Input.txt", "r");
i=0;
InsertionSort(a, n);
getch();
}
OUTPUT
Do yourself
DISCUSSION
It finds that both 14 and 33 are already in ascending order. For now, 14 is
in sorted sub-list.
This process goes on until all the unsorted values are covered in a sorted
sub-list.
Time Complexity
• Best case: O(n), If the list is already sorted, where n is the number of
elements in the list.
• Average case: O(n2), If the list is randomly ordered
• Worst case: O(n2), If the list is in reverse order
Space Complexity
• Auxiliary Space: O(1)