This is the most common sort method in the sorting algorithm, and is also the most used by beginners. Sometimes we unconsciously use the insertion sort in our life, for example:
Sort the cards in hand
This is one of the most common examples where we usually start from the side of the card, find an incorrect position, take it out, and start at the starting position until we find the right place to insert the card.
Suppose you have these cards in your hand 2,4,6,3,10,k,j. The steps for sorting are as follows:
- Let's say we start from the left, 2 is right, 4 is right, 6 is right, 3 is wrong, he is smaller than the previous 6.
- Need to re-find the correct location for 3.
- Take out 3 of this card, punch start to look, 3:2 big, then back, 3:4 small, so 3 insert position between 2 and 4. Now the order of cards has become 2,3,4,6,10,k,j.
- Then the last time we left the point to see (that is, 3 of the position, now becomes 6), 6 is correct, 10 position is correct, k position is correct, j position is incorrect, because he is smaller than the previous K.
- Take J out and start looking again, J is bigger than 2,3,4,6,10, smaller than K, so it's between 10 and K.
The sorting is done, and the cards in the hand become the correct order, and this method is called the insertion sort.
The corresponding algorithm design:
- Start scanning the elements from 2nd position. The 1st is assumed to being at correct place.
- if (Arr[i] < arr[i-1])
- Swap Arr[i] and arr[i-1]
- Keep swapping until the number is less than the previous number
- The array gets sorted as we reach the end.
Here is the specific execution code:
#include <stdio.h>//function to swap integersvoidSwapint*x,int*y) { inttemp = *x; *x = *y; *y =temp;} //a function to perform insertion Sort on the array arr with size specifiedvoidInsertionsort (intArr[],intsize) { inti,j; //iterating from 2nd element to the last for(i=1; i<size;i++) { if(Arr[i] < arr[i-1]) {J=i; while(arr[j-1] >Arr[j]) { //swapping all the numbers//until the next number is smaller than previous numberSwap (&arr[j],&arr[j-1]); J--; } } }} //driver function to test the above functionintMainvoid){ inti; intarr[Ten] = {3,4,7,1,Ten,8,2, A, About, -}; Insertionsort (arr,Ten); printf ("SORTED array:-"); for(i=0;i<Ten; i++) printf ("%d", Arr[i]); return 0;}
Complexity of Time:
Average case:-O (n2)
Best case:-O (n)
Worst case:-O (N2)
Insert sort (Insertion sort)