Objective:To learn about Insertion sort algorithm,know how it works and use it in real life.
Application: Suppose there exists a function called Insert designed to insert a value into a sorted sequence at the beginning of an array. It operates by beginning at the end of the sequence and shifting each element one place to the right until a suitable position is found for the new element. The function has the side effect of overwriting the value stored immediately after the sorted sequence in the array.To perform an insertion sort, begin at the left-most element of the array and invoke Insert to insert each element encountered into its correct position. The ordered sequence into which the element is inserted is stored at the beginning of the array in the set of indices already examined. Each insertion overwrites a single value: the value being inserted.
Pseudocode:
// The values in A[i] are checked in-order, starting at the second one for i ← 1 to i ← length(A) { // at the start of the iteration, A[0..i-1] are in sorted order // this iteration will insert A[i] into that sorted order
// save A[i], the value that will be inserted into the array on this iteration valueToInsert ← A[i] // now mark position i as the hole; A[i]=A[holePos] is now empty holePos ← i // keep moving the hole down until the valueToInsert is larger than // what's just below the hole or the hole has reached the beginning of the array while holePos > 0 and valueToInsert < A[holePos - 1] { //value to insert doesn't belong where the hole currently is, so shift A[holePos] ← A[holePos - 1] //shift the larger value up holePos ← holePos - 1 //move the hole position down } // hole is in the right position, so put valueToInsert into the hole A[holePos] ← valueToInsert // A[0..i] are now in sorted order }
Source Code: import java.io.*; class insertion {