Insertion Sort is a comparison-based sorting algorithm where elements are moved one by one to their correct position in a growing sorted portion of the array.
Array before sorting: [5, 3, 8, 4, 2]
Time Complexity:
Space Complexity: O(1) - only requires a constant amount of additional space.
The following is the pseudo code for Insertion Sort:
Begin
for i = 1 to n-1
key = arr[i]
j = i - 1
while j >= 0 and arr[j] > key
arr[j + 1] = arr[j]
j = j - 1
arr[j + 1] = key
End
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 = j - 1; } arr[j + 1] = key; }