What is Insertion Sort in Java

Insertion Sort is a simple sorting algorithm that sorts an array by comparing each element with its adjacent elements and swapping them if they are not in the correct order. This process is repeated for each element in the array, resulting in a sorted array.


Here's how it works:


  1. 1. Iterate through the array from the second element to the last.

  2. 2. For each element, compare it with the elements before it until you find the correct position to insert it.

  3. 3. Shift the larger elements to the right to make space for the current element.

  4. 4. Insert the current element into its correct position.

  5. 5. Repeat steps 2 to 4 for the remaining elements in the array.

For example, let's say we have an unsorted array:

[5, 3, 8, 6, 7, 2]


  1. 1. Starting with the second element (3), compare it with the first element (5). Since 3 is smaller, we swap them to get [3, 5, 8, 6, 7, 2].

  2. 2. Now compare 8 with 5, and since 8 is larger, we leave it where it is.

  3. 3. Compare 6 with 8, then with 5, and finally with 3. We find that 6 should be inserted between 5 and 8, so we shift 8 and 5 to the right to get [3, 5, 6, 8, 7, 2].

  4. 4. Similarly, we insert 7 between 6 and 8, and insert 2 between 3 and 5 to get the sorted array: [2, 3, 5, 6, 7, 8].

Here's the Java code for implementing Insertion Sort:

public class InsertionSort {
    public static void main(String[] args) {
        int[] arr = {5, 3, 8, 6, 7, 2};
        int n = arr.length;
        
        for (int i = 1; i < n; i++) {
            int key = arr[i];
            int j = i - 1;
            
            while (j >= 0 && arr[j] > key) {
                arr[j+1] = arr[j];
                j--;
            }
            arr[j+1] = key;
        }
        
        for (int i = 0; i < n; i++) {
            System.out.print(arr[i] + " ");
        }
    }
}


In this code, we first declare and initialize the array arr and its length n. We then start iterating through the array from the second element (i=1), and for each element, we compare it with the elements before it (j). If the previous element is larger, we shift it to the right to make space for the current element (arr[j+1] = arr[j]), and continue comparing with the previous elements. When we find the correct position for the current element, we insert it into the array (arr[j+1] = key). Finally, we print out the sorted array.