Easy Tutorial
❮ Python String Split Python Func Set ❯

Python Insertion Sort

Python3 Examples

Insertion Sort is a simple and intuitive sorting algorithm. It works by building a sorted sequence. For the unsorted data, it scans backward through the sorted sequence to find the appropriate position and inserts it.

Example

def insertionSort(arr): 

    for i in range(1, len(arr)): 

        key = arr[i] 

        j = i-1
        while j >=0 and key < arr[j] : 
                arr[j+1] = arr[j] 
                j -= 1
        arr[j+1] = key 


arr = [12, 11, 13, 5, 6] 
insertionSort(arr) 
print ("Sorted array:") 
for i in range(len(arr)): 
    print ("%d" %arr[i])

Execution of the above code produces the following result:

Sorted array:
5
6
11
12
13

Python3 Examples

❮ Python String Split Python Func Set ❯