Back to DSA Course

DSA Course

Insertion sort is a simple sorting algorithm that works the way we sort playing cards in our hand. We choose one card and insert in its position.

This is useful only for sorting small set of elements.

Pick element and insert it into sorted sequence

For example,

int[] num = { 90, 24, 46, 35, 32 };

Lets see how insertion sort works

90,24,46,35,32 24,90,46,35,32 24,46,90,35,32 24,35,46,90,32 24,32,35,46,90

Let's start coding for insertion sort

package com.praveen.sort; import java.util.Arrays; public class InsertionSort { public static void main(String[] args) { int[] arr = { 90, 24, 46, 35, 32 }; insertion(arr); System.out.println(Arrays.toString(arr)); } private static void insertion(int[] arr) { for (int i = 0; i < arr.length - 1; i++) { for (int j = i + 1; j > 0; j--) { if (arr[j] < arr[j - 1]) { swap(arr, j, j - 1); } else { break; } } } } private static void swap(int[] arr, int first, int second) { int temp = arr[first]; arr[first] = arr[second]; arr[second] = temp; } }

Output

[24, 32, 35, 46, 90]