Insertion Sort Python Program

  Python program for Insertion sort, Insertion sort is the best way to sort the data. The following program shows the implementation of Insertion Sort algorithms in Python Programming Language.

Insertion Sort Python Program

   
 

def insertionSort(nums):
    if not nums or len(nums) < 2:
        return nums

    for i in range(1, len(nums)):
        for j in range(i):
            if nums[i] < nums[j]:
                nums[i], nums[j] = nums[j], nums[i]
    return nums


if __name__ == "__main__":
    nums = [55,3,2,99,0,1,5,7,8]
    print('Before Sort: ', nums)
    nums = insertionSort(nums)
    print("After Sort: ", nums)




Output

Before Sort: [55, 3, 2, 99, 0, 1, 5, 7, 8]
After Sort: [0, 1, 2, 3, 5, 7, 8, 55, 99]

Leave a Reply

Your email address will not be published. Required fields are marked *