Insertion Sort - Insertion sort is a simple sorting
algorithm that is relatively efficient for small lists and mostly sorted lists.
It works by taking elements from the list one by one and inserting them in
their correct position into a new sorted list. In this technique instead
swapping value is shifted to the correct position.
Worst-Case Analysis
·
The outer loop is always done N – 1 times
·
The inner loop does the most work when the next element is smaller
than the past elements
·
On each pass, the next element is compared to all earlier
elements, giving:
·
Running time in this case?
·
inner loop test executes p+1 times for each p
N-1
Σ i = 2 + 3 + 4 + … +
N = θ(N2)
i=1
Insertion sort is O(N2) on average
Insertion Sort Source Code and Algorithm.
#include <stdio.h>
#include <conio.h>
// INSERTION SORT
//Function Called for Sorting
void InsertionSort(int a[],int
size)
{
int i,j;
int e;
for(i=1;i<size;i++)
{
e = a[i];
j=i;
while(j>0
&& a[j-1]>e)
{
a[j] =
a[j-1];
j--;
}
a[j]=e;
}
}
//Main Function
void main()
{
int i,n,c=0;
int a[20];
clrscr();
printf("\n\tEnter
size of Array [Below 20] : ");
scanf("%d",&n);
for(i=0 ;i<n;i++)
{
printf("\tEnter Nos. at [%d] :
",i);
scanf("%d",&a[i]);
}
printf("\n\tBefore
Sort : ");
for(i=0 ;i<n;i++)
{
printf("%d ",a[i]);
}
printf("\nA\tfter
Sort : ");
InsertionSort(a,n);
for(i=0 ;i<n;i++)
{
printf("%d ",a[i]);
}
getch();
}
Algorithm.
for i ← 1 to n-1 do
do
value ← A[i];
j ← i;
while j>0 &&
A[j-1] > value
do
A[j ] ← A[j-1];
j ← j - 1;
end
A[j] ← value;
end for i
Insertion Sort using Recursive Function.
#include <stdio.h>
#include <conio.h>
//Recursive Insertion Sort
int a[20];
// Function for inner loop
void Isrt(int a[], int j, int
num)
{
int flag = 0;
if (a[j] > num)
{
a[j + 1] = a[j];
if (--j <
0)
{
flag =
1;
}
}
else
{
flag = 1;
}
if (flag)
{
a[j + 1] = num;
}
else
{
Isrt(a, j, num);
}
}
// Finction for outer loop
void ISort(int a[], int n)
{
static int i;
int j = i, num;
if (++i < n)
{
num = a[i];
Isrt(a, j, num);
ISort(a, n);
}
else
{
i = 0;
}
}
// Main function
void main()
{
int i, j, n,t;
int a[20];
clrscr();
printf("\n\tEnter
Size of Arry (Below 20) : ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\nEnter
%d Values ",n);
scanf("%d",&a[i]);
}
printf("\n\tOriginal : ");
for(i=0;i<n;i++)
{
printf(" %d
",a[i]);
}
ISort(a, n);
printf("\n\tSorted ");
for(i=0;i<n;i++)
{
printf("
%d ",a[i]);
}
getch();
}