Enter an array separated by commas as : 16,15,15,10,1 or just press the hand icon to generate a random array then press enter or Sort button. Sorting will start and you can watch each pass as it gets sorted. When it shows green it means the two of them are being compared when red shows, it means the left number is greater than right number so it needs swapping The blue color means the number is at its correct position and thus sorted it will continue to check other numbers until it reaches end.
Insertion sort is one of the oldest sorting algorithms, dating back to the early days of computer science. It is inspired by the way people sort playing cards: by taking one card at a time and inserting it into its correct position within an already sorted portion of the deck.
First documented in the 1950s, it was commonly used in early computer systems due to its simplicity and ease of implementation. It was often used for sorting small data sets or nearly sorted data.
O(n)
– When the array is already sorted.O(n2)
– Quadratic complexity for average
cases.
O(n2)
– When the array is sorted in reverse
order.
Space Complexity: O(1)
– It is an in-place sorting algorithm requiring
a
constant amount of additional space.
function insertionSort(arr):
for i from 1 to length(arr) - 1:
key = arr[i]
j = i - 1
/* Move elements of arr[.0..i-1] that are greater than key
to one position ahead of their current position */
while j >= 0 and arr[j] > key:
arr[j + 1] = arr[j]
j = j - 1
arr[j + 1] = key
return arr
Insertion sort is a straightforward and efficient algorithm for small or nearly sorted datasets.
Despite
its O(n2)
worst-case complexity, it remains popular in certain applications
due to its
simplicity, low overhead, and adaptive nature.