Insertion Sort

#!/usr/bin/evn python

# Function for insertion sort
def insertionSort(data):
    # Loop the process within range of number list
    for i in range(1,len(data)):
        currentVal = data[i]
        pos = i
        
        # Compare upto position 'i' and swap
        while pos > 0 and data[pos-1] > currentVal:
            data[pos]=data[pos-1]
            pos = pos-1

        data[pos] = currentVal
        
numList = [5,8,1,6,3,7,2,4,9]
print('Before sort:')
print(numList)
# Calling 'insertionSort' function by passing number array
insertionSort(numList)
print('After sort:')
print(numList)


# ***** Output *****
Before sort:
[5, 8, 1, 6, 3, 7, 2, 4, 9]
After sort:
[1, 2, 3, 4, 5, 6, 7, 8, 9]

Recommended for you