It is the kind of sorting algorithm that works by iterating over an array and inserting each element at its correct position in the sorted part of the array.
Space Complexity – O(1)
Best Case Time Complexity – O(N). This case will occur if the array is already sorted where the outer loop runs from 0 to n and the inner loop runs 0 times.
import java.util.*; public class Main { public static void main(String[] args) { int arr[]= {5,4,10,1,6,2}; insertionSort(arr); for(int i:arr){ System.out.println(i); } } public static void insertionSort(int arr[]){ for(int i=0;i<arr.length;i++){ int j=i; while(j>0 && arr[j-1]>arr[j]){ int temp=arr[j-1]; arr[j-1]=arr[j]; arr[j]=temp; j--; } } } }