Python Program to sort an array using Insertion Sort

Program

def insertionSort(arr, n):
    for i in range(n):
        temp = arr[i]
        j = i - 1
        while (temp < arr[j]) and (j >= 0):
            arr[j+1] = arr[j]
            j = j - 1
        arr[j + 1] = temp
    print("Sorted array:")
    for i in range(n):
        print("%d" % arr[i])
print("Enter the size of the array:")
n = int(input())
arr = []
print("Enter array elements:")
for i in range(n):
    x = int(input())
    arr.append(int(x))
insertionSort(arr, n)

Output

Enter the size of the array:
6
Enter array elements:
-43
0
-8
856
12
96
Sorted array:
-43
-8
0
12
96
856

Tags: