insertion sort – Programmerbay https://programmerbay.com A Tech Bay for Tech Savvy Tue, 29 Sep 2020 07:53:15 +0000 en-US hourly 1 https://wordpress.org/?v=6.5.5 https://programmerbay.com/wp-content/uploads/2019/09/cropped-without-transparent-32x32.jpg insertion sort – Programmerbay https://programmerbay.com 32 32 C Program to sort an array using Insertion sort in Ascending order https://programmerbay.com/program-to-sort-an-array-using-insertion-sort/ https://programmerbay.com/program-to-sort-an-array-using-insertion-sort/#respond Tue, 09 Jun 2020 18:33:09 +0000 https://www.programmerbay.com/?p=2846 The program sorts an array based on given input. There are bunch of sorting techniques such as Bubble sort, Selection sort and more to achieve this functionality. In this, we’ll be discussion Insertion Sort technique.

Insertion sort

In this sorting technique, the number that needs to be sorted is known as Key. This algorithm is efficient for sorting a small unit of elements.

It can be considered as a way that people use to sort playing cards. A set of cards facing towards the table are picked one by one and put at their correct place.

we compare a new card lifted from the table with the existing ones in our hand.

playing cards

Similarly, in insertion sort at each iteration, an element from the input dataset is taken out and placed to the location where it belongs to be. It is followed until all the inputs get placed and sorted.

Pseudocode

for j=1 to Array.Length

key=arr[j]
k=j-1;
while k>=0 && arr[k]>key
arr[k+1] = arr[k]
arr[k]=key
k= k-1
End While
End for

C program to sort an array using Insertion Sort in Ascending Order

#include<conio.h>
#include<stdio.h>
#define size 6
void main()
{
int arr[size],i,j,k,key,temp;
printf("Please enter elements: \n "); 
for(i=0;i<=size-1;i++)
{
scanf("%d",&arr[i]);
}

for(j=1;j<=size-1;j++)
{
key=arr[j];
k=j-1;
while (k>=0 && arr[k]>key)
{
arr[k+1] = arr[k];
arr[k]=key;
k=k-1;
}
}

printf(" \n Entered Elements :");

for(i=0;i<=size-1;i++)
{
printf("\n %d ",arr[i]);
} 
getch();
}

 

Output:

insertion sort

How does it work?

insertion sort working

It requires a constant amount O(1) of additional memory space and O(n2) comparisons in the worst case and average case to sort an array.

However, sorting time to sort the same size of elements can be varied depending on how much a given array is already sorted.

]]>
https://programmerbay.com/program-to-sort-an-array-using-insertion-sort/feed/ 0