Insertion Sort builds the final sorted array one item at a time. It is much like sorting playing cards in your hands:
Itβs efficient for small or nearly sorted datasets.
public class InsertionSortExample {
public static void insertionSort(int[] arr) {
int n = arr.length;
for (int i = 1; i < n; i++) {
int key = arr[i];
int j = i - 1;
// Shift elements of arr[0..i-1] that are greater than key
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
// Print the array after each insertion
printArray(arr);
}
}
public static void printArray(int[] arr) {
for (int value : arr) {
System.out.print(value + " ");
}
System.out.println();
}
public static void main(String[] args) {
int[] arr = {12, 11, 13, 5, 6};
System.out.println("Original array:");
printArray(arr);
System.out.println("\nSorting steps:");
insertionSort(arr);
System.out.println("\nSorted array:");
printArray(arr);
}
}
Original array:
12 11 13 5 6
Sorting steps:
11 12 13 5 6
11 12 13 5 6
5 11 12 13 6
5 6 11 12 13
Sorted array:
5 6 11 12 13
[12, 11, 13, 5, 6]
i = 1, key = 11Compare with 12 β shift 12 to the right β insert 11 before it
[11, 12, 13, 5, 6]
i = 2, key = 1313 > 12 β no shifting needed
[11, 12, 13, 5, 6]
i = 3, key = 55 < 13 β shift 13
5 < 12 β shift 12
5 < 11 β shift 11
Insert 5 at position 0
[5, 11, 12, 13, 6]
i = 4, key = 66 < 13 β shift 13
6 < 12 β shift 12
6 < 11 β shift 11
Insert 6 at position 1
[5, 6, 11, 12, 13]
[5, 6, 11, 12, 13]