# What is Insertion sort in Python?

PythonServer Side ProgrammingProgramming

Insertion sort is the simple method of sorting an array. In this technique, the array is virtually split into the sorted and unsorted part. An element from unsorted part is picked and is placed at correct position in the sorted part.

• The array elements are traversed from 1 to n.

• If the array element at position i is greater than its predecessor, it does not need to be moved.

• If the array element at position i is less than its predecessor, it needs to be shifted towards left until we find a predecessor smaller than it or if we reach at the leftmost position in the array.

Example

We can understand the above idea more clearly with the help of an example. Suppose we have the following array −

 4 6 1 7 2 5

We need to start traversing the array from index 1(because index 0 has no predecessor).

At index 1

6 is greater than its predecessor, hence nothing needs to be done.

 4 6 1 7 2 5

At index 2

 4 6 1 7 2 5

1 is less than its predecessor, hence we need to shifr it leftwards unless we find a predecessor smaller than it or if we reach index 0.In this case we will reach index 0.

 4 6 1 7 2 5

At index 3

 1 4 6 7 2 5

At index 4

 1 4 6 7 2 5

Shift 2 leftwards, until we find a predecessor smaller than 2.

 1 2 4 6 7 5

At index 5

 1 2 4 6 7 5

Shift 5 leftwards, until we find a predecessor smaller than 5.

 1 2 4 5 6 7

Hence, we obtain the sorted array.

The insertion sort is an in-place sorting algorithm with O(n^2) time complexity and O(1) space complexity.

## Example

def insertionSort(arr):
for i in range(1, len(arr)):
key = arr[i] #get each element
j = i-1
while j >= 0 and key &lit; arr[j] : #keep shifting until reaching index 0 or getting an element smaller than key
arr[j + 1] = arr[j]
j=j-1
arr[j + 1] = key

arr = [4,6,1,7,2,5]
insertionSort(arr)
for i in range(len(arr)):
print (arr[i],end=" ")

## Output

1 2 4 5 6 7
Updated on 11-Jun-2021 12:50:08