Insertion Sort
Insertion Sort is a simple and intuitive sorting algorithm that builds the final sorted array one element at a time. It is particularly efficient for small or nearly sorted datasets.
key
) and compare it with the elements in the sorted portion (to its left).key
one position to the right.key
into its correct position in the sorted section.for i = 1 to length(array) - 1:
key = array[i]
j = i - 1
while j >= 0 and array[j] > key:
array[j + 1] = array[j]
j = j - 1
array[j + 1] = key
O(n)
when the array is already sorted.O(n²)
due to the nested loop in the worst scenario.https://drawtocode.vercel.app/problems/insertion-sort
Loading component...
Loading component...
INPUT: int [] arr = {4,3,2,1};
OUTPUT: arr = {1,2,3,4}
public static void main(String[] args){
int[] arr = { 64, 25, 12, 22, 11 };
System.out.print("Original array: ");
printArray(arr);
insertionSort(arr);
System.out.print("Sorted array: ");
printArray(arr);
} // Function End
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;
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j--;
}//Loop End
arr[j + 1] = key;
}//Loop End
}//function end
static void printArray(int[] arr){
for (int val : arr) {
System.out.print(val + " ");
}//Loop End
System.out.println();
} // Function End