TOPIC NAME :
INSERTION SORT
What Is Insertion Sort?
Insertion sort is a simple sorting algorithm that
builds a sorted list one item at a time by taking an
element from the unsorted part and inserting it
into its correct position within the already sorted
part.
How It Works:
The algorithm assumes the first element is
sorted and then considers the rest of the array
one by one . For each new elements, it
compares it to the elements in the sorted portion,
moving backwards and shifting larger elements
to the right until the correct spot is found for the
new element.
Insertion Sort Algorithm:
Insertion sort(A[0……..n-1],n)
A is an array of n elements.
step 1: repeat step 2 to 5 for 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
Insertion sort:
Program : program to sort n Numbers using Insertion sort
#include< stdio.h >
Void insertion_sort (int a[], int n)
{
int pass,k,temp,j;
for(pass=1; pass<n; pass++)
{
k=A[pass];
for(j=pass-1; j>=0 && k<a[j]; j--)
{
A[j+1]=A[j];
}
A[j+1]=K
}
}
void main()
{
int i, A[100],n;
printf("enter the number of elements:");
scanf("%d",& n);
printf("\n enter the array elements:");
for(i=0;i<n;i++)
scanf("%d",& A[i]);
insertion_sort(A, n);
printf("\n the final sorted array is:");
for(i=0;i<n;i++)
printf("%d",& A[i]);
}
Output:
Enter the number of elements:5
Enter the array elements:90 65 36 77 81
The final sorted array is :36 65 77 81 90