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...