Insertion sort
One element from the array is selected and is compared to the one side of the array and inserted to the proper position while shifting the rest of the elements accordingly.
Insertion algorithm
Insertion algorithm selects one element from start (position 2nd, C array index =1). It is saved to a temporary variable. Then it is compared to the left side elements one by one. If the element is bigger then the selected element, it is shifted to right. A hole is created while this shifting. Then this process is repeated till index reaches to first element. Element is not moved when value is less than the selected element. The hole is not shifted in this case. Now finally the selected element (from the temporary variable) is moved to hole. Now this element reached to its proper position. After this the next position or array index 2 is selected. Then we repeat the same process. Gradually all the left side elements are moved and becomes sorted. This entire process repeats till selection of array position goes to max (count-1). Finally entire array is sorted and selected element is inserted to its proper position.
Insertion sort example code
Code: Insertion Sort of 5 integer elements in ascending order.
Steps and Iterations (diagrams)
Output
Insertion sort 4, 9, 5, 1, 0, Position #1 value 9 4, 9, 5, 1, 0, insert @1 = 9 4, 9, 5, 1, 0, Position #2 value 5 4, 9, 5, 1, 0, move 9 -> 5 4, 9, 9, 1, 0, insert @1 = 5 4, 5, 9, 1, 0, Position #3 value 1 4, 5, 9, 1, 0, move 9 -> 1 4, 5, 9, 9, 0, move 5 -> 9 4, 5, 5, 9, 0, move 4 -> 5 4, 4, 5, 9, 0, insert @0 = 1 1, 4, 5, 9, 0, Position #4 value 0 1, 4, 5, 9, 0, move 9 -> 0 1, 4, 5, 9, 9, move 5 -> 9 1, 4, 5, 5, 9, move 4 -> 5 1, 4, 4, 5, 9, move 1 -> 4 1, 1, 4, 5, 9, insert @0 = 0 0, 1, 4, 5, 9, Press any key to continue
Further readings
- www.geeksforgeeks.org - insertion-sort
- www.tutorialspoint.com - insertion-sort
- www.hackerearth.com - insertion-sort
- wikipedia.org - insertion-sort
- www.interviewbit.com - insertion-sort
About our authors: Team EQA
You have viewed 1 page out of 252. Your C learning is 0.00% complete. Login to check your learning progress.