Insertion Sort Algorithm

Insertion Sort:

Insertion sort is a simple sorting algorithm that is relatively efficient for small lists and mostly sorted lists, and is often used as part of more sophisticated algorithms. It works by taking elements from the list one by one and inserting them in their correct position into a new sorted list.[17] In arrays, the new list and the remaining elements can share the array’s space, but insertion is expensive, requiring shifting all following elements over by one. Shell sort (see below) is a variant of insertion sort that is more efficient for larger lists.

Time Complexity of Insertion Sort :
Class Sorting algorithm
Data structure Array
Worst case performance О(n2) comparisons, swaps
Best case performance O(n) comparisons, O(1) swaps
Average case performance О(n2) comparisons, swaps
Worst case space complexity О(n) total, O(1) auxiliary
Animated Example :


Psedo Code :
public static void insertionSort(int[] array) {
for (int i = 0; i < array.length - 1; i++) {
int j = i + 1;
int tmp = array[j];
while (j > 0 && tmp > array[j-1]) {
array[j] = array[j-1];
array[j] = tmp;
Complete Code :
public class InsertionSort {
public static void main(String args[]){

int a[]={1,3,5,6,12,22,12,7,8,9};


public static void intInsertionSort(int[] a){
for (int i = 1; i <a.length ; i++) {
int temp = a[i];
int j;
for ( j = i-1; j >=0 && temp<a[j] ; j--) {

a[j+1] = a[j];

a[j+1] =temp;


public static void printNumbers(int[] input){
for (int i = 0; i <input.length ; i++) {
System.out.print(input[i] + "," );


Leave a Reply

Your email address will not be published. Required fields are marked *