Insertion Sort

Insertion Sort

Algorithm Steps

  1. Start from the second element (index 1) of the array.
  2. Set the current element as the key.
  3. Compare the key with the elements before it.
  4. Shift all elements that are greater than the key one position to the right.
  5. Insert the key into its correct position.
  6. Repeat the process for all elements until the array is sorted.

Insertion Sort Program Code

Python
Java
JavaScript
C
C++
C#
Kotlin
Swift
Go
Php
def insertion_sort(arr):
    for i in range(1, len(arr)):
        key = arr[i]
        j = i - 1
        while j >= 0 and arr[j] > key:
            arr[j + 1] = arr[j]
            j -= 1
        arr[j + 1] = key
    return arr

if __name__ == '__main__':
    arr = [6, 3, 8, 2, 7, 4]
    insertion_sort(arr)
    print("Sorted array is:", arr)