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:
For example, let's say we have an unsorted array:
[5, 3, 8, 6, 7, 2]
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.