Insertion Sorting in C - (Algorithm with Example)

In today's article, we will learn about insertion shorting in c. Its working, algorithm, and example | So first of all, know what is the insertion shorting.


Insertion-Sorting-in-C


What is Shorting?


Many times programmers work with more data and it is necessary to keep that data in decreasing and increasing order.

 

What is Insertion Shorting?


Insertion shorting is a shorting technique. insertion shorting is useful for small data sets.it is not useful for large data sets.


This technique of insertion shoring consists of n elements. From which only one element is taken at a time. these are arranged in the pattern of element array. this insertion of array shot is called insertion shorting.


Working Insertion Shorting


  1. In this, the first element is raised, is an element, it is considered as the shorted portion of the array.
  2. Then it compares the first two elements with the left.
  3. If the first element is larger than the second, then their position is swapped, the smaller value comes forward.
  4. If an element is already sorted then there is no need to do shorting then comparison to the next element.
  5. This shorting continues until the elements of the array are completed.
  6. When shorting completes, all the small elements move from left to right in increasing order of right.


Algorithm Insertion Shorting


Suppose we have the input element in the array as follows.

Insertion-Sorting-in-C

Insertion 0       10 , 5 , 8 , 6 , 7

1.On comparing the first two elements

 

Insertion 1     5 , 10 , 8 , 6 , 7

2.Since 10> 5, they will swap among themselves

 

Insertion 2      5 , 8 , 10 , 6 , 7

3.Now compare 8 and 10 where 10> 8 is

 

Insertion 3      5 , 6 , 8 , 10 , 7

4.Now compare 10 and 6 where 10> 6 but 6 is still unsorted. Now 8> 6, they will swap among themselves.

 

Insertion 4      5 , 6 , 7 , 8 , 10

5.Similarly, if there is 10> 7 then there will be swap and if there is 8> 7 then there will be swap


Shorting

Insertion 0 =  10,5,8,6,7

Insertion 1 =  5,10,8,6,7

Insertion 2 =  5,8,10,6,7

Insertion 3 =  5,6,8,10,7

Insertion 4 =  5,6,7,8,10


Insertion Shorting Program In C


#include <stdio.h>

int main ()

{

   int n, i, j, temp;

   int arr [64];

  printf ("Enter number of Elements \ n");

  scanf ("% d", & n);

  printf ("Enter% d integers \ n", n);

  for (i = 0; i <n; i ++)

  {

    scanf ("% d", & arr [i]);

  }

 for (i = 1; i <= n - 1; i ++)

 {

j = i;

     while (j> 0 && arr [j-1]> arr [j])

     {

        temp = arr [j];

       arr [j] = arr [j-1];

       arr [j-1] = temp;

       j--;

     }

   }

  printf ("Sorting in ascending order: \ n");

  for (i = 0; i <= n - 1; i ++)

 {

  printf ("% d \ n", arr [i]);

  }

 return 0;

}


Input 

Enter number of Elements 5

Enter 5 integers 

5
4
3
2
1

Output

Sorting in ascending order:
1
2
3
4
5

Post a Comment

0 Comments