Insertion sort is a simple sorting algorithm that works by iteratively inserting elements into a sorted subset of the array. It has a worst case time complexity of O(n^2) but performs well on small or partially sorted data. The algorithm splits the array into a sorted and unsorted part, taking elements from the unsorted part and inserting them into the correct position in the sorted part until the entire array is sorted.
3. THEORY
Insertion sort is a simple sorting algorithm that works similar to the way you sort playing cards in
your hands. The array is virtually split into a sorted and an unsorted part. Values from the unsorted
part are picked and placed at the correct position in the sorted part.
This algorithm is one of the simplest algorithm with simple implementation.
Basically, Insertion sort is efficient for small data values.
Insertion sort is adaptive in nature, i.e. it is appropriate for data sets which are already partially
sorted.
It requires (n-1)passes.
Insertion Sort Applications
The insertion sort is used when:
• the array is has a small number of elements
• there are only a few elements left to be sorted
4.
5. #include<stdio.h>
int main()
{
int i, j, count, temp, number[25];
printf("How many numbers u are going to enter?: ");
scanf("%d",&count);
printf("Enter %d elements: ", count);
for(i=0;i<count;i++) // This loop would store the input numbers in array
scanf("%d",&number[i]);
for(i=1;i<count;i++) // Implementation of insertion sort logic
{
temp=number[i];
j=i-1;
while((temp<number[j])&&(j>=0))
{
number[j+1]=number[j];
j=j-1;
}
number[j+1]=temp;
}
C Program
7. Algorithm
Step 1: Start
Step 2: Set temp=0,i=1,j=0
Step 3: Repeat step 4 to 12 while (i<size)
Step 4: set temp=a[i]
Step 5: set j=i-1
Step 6: Repeat step 7 to 10 while (i>=0)
Step 7: if (a[j]>temp) goto step 8 else goto step 9
Step 8: Set a[j+1]= a[j]
Step 9: branch out and goto step 11
Step 10: set j=j-1
Step 11:Set a[j+1]= temp
Step 12: i=i+1
Step 13:stop
8. PSEUDOCODE
procedure insertionSort( A : array of items )
int holePosition
int valueToInsert
for i = 1 to length(A) inclusive do:
/* select value to be inserted */
valueToInsert = A[i]
holePosition = i
/*locate hole position for the element to be inserted */
while holePosition > 0 and A[holePosition-1] > valueToInsert do:
A[holePosition] = A[holePosition-1]
holePosition = holePosition -1
end while
/* insert the number at hole position */
A[holePosition] = valueToInsert
end for
end procedure
9. TIME COMPLEXITY
Best case
Worst case
Average case
First for loop Second for loop
O(n) O(1)
Total
O(n)
O(n)
O(n)
O(n)
O(n) O(n)2
O(n)2