Insertion sort is a straightforward sorting algorithm that processes a collection (often an array or list) from left to right, maintaining a growing sorted prefix. For each element, it finds the correct position within the already-sorted portion and inserts it there, shifting larger elements to the right as needed.
Given [5, 2, 4, 6, 1, 3]:
for i from 1 to n-1: # 0-based indexing
key = A[i]
j = i - 1
while j >= 0 and A[j] > key:
A[j + 1] = A[j]
j = j - 1
A[j + 1] = keydef insertion_sort(a):
for i in range(1, len(a)):
key = a[i]
j = i - 1
while j >= 0 and a[j] > key:
a[j + 1] = a[j]
j -= 1
a[j + 1] = key
return afunction insertionSort(arr) {
for (let i = 1; i < arr.length; i++) {
const key = arr[i];
let j = i - 1;
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = key;
}
return arr;
}