Insertion Sort

Insertion sort uses linear search to find the location of the 1st element in the unsorted list, in the sorted portion of the list. It is an elementary sorting algorithm best used to sort small data sets or insert a new element in the sorted list.

Algorithm:
Insertion sort starts with a sorted list of size 1 and inserts elements one at a time. It continues inserting each successive element into the sorted list so far.

1. Suppose if the array is sorted till index i then we can sort the array till i+1 by inserting i+1th element in the correct position from 0 to i+1.
2. The position at which (i+1)th element has to be inserted has to be found by iterating from 0 to i.
3. As any array is sorted till 0th position (Single element is always sorted) and we know how to expand, we can sort the whole array.
for i ← 1 to length(A) - 1
j ← i
while j > 0 and A[j-1] > A[j]
swap A[j] and A[j-1]
j ← j - 1
end while
end for

Property:
1. Best case performance – When the array is already sorted O(n). Total number of comparisons: N – 1 and total number of exchanges: N – 1.
2. Worst case performance – When the array is sorted in reverse order O(n2). N-1 iterations of comparison and exchanges.
3. Average case performance – O(n2)
4. It is sensitive to the input as the number of comparison and exchanges depends on the input.
5. It does not require any extra space for sorting, hence O(1) extra space.

Insertion Sort in Java :

import java.util.*;
import java.lang.*;
import java.io.*;

class InsertionSort
{
public static void main (String[] args) throws java.lang.Exception
{
int[] input = {4, 2, 9, 6, 23, 12, 34, 10, 5};
insertionSort(input);
}

private static void printNumbers( int[] input) {
for (int i = 0; i < input.length; i++) {
System.out.println( input[i] + “, “);
}
System.out.println(“\n”);
}

public static void insertionSort( int array[]) {

int n = array.length;
for(int j = 1; j < n ; j++) {
int key = array[j];
int i = j – 1;
while( (i> -1) && (array[i]) > key) {
array[i+1] = array[i];
i–;
}
array[i+1] = key;
printNumbers(array);
}
}
}