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.
What is Shorting?
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
- In this, the first element is raised, is an element, it is considered as the shorted portion of the array.
- Then it compares the first two elements with the left.
- If the first element is larger than the second, then their position is swapped, the smaller value comes forward.
- If an element is already sorted then there is no need to do shorting then comparison to the next element.
- This shorting continues until the elements of the array are completed.
- 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 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
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
int main ()
int n, i, j, temp;
int arr ;
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;
printf (“Sorting in ascending order: n”);
for (i = 0; i <= n – 1; i ++)
printf (“% d n”, arr [i]);
Enter number of Elements 5Enter 5 integers54321
Sorting in ascending order:12345
Recommend: Call By Value And Call By Reference