Join 36000+ teachers and students using TTIO.
Insertion sort is a simple sorting algorithm that builds the final sorted array (or list) one item at a time. It is a comparison-based algorithm that builds a final sorted array one element at a time. It iterates through an input array and removes one element per iteration, finds the place the element belongs in the array, and then places it there.
It is generally considered much less efficient on large lists than more advanced algorithms such as quicksort, heapsort, or merge sort although it does has its own advantages - see additional information below.
#1 Write a Python program to sort a list of elements using the Insertion sort algorithm
#2 Comment each line of the python solution below to show your understanding of the algorithm
def insertionSort(nlist): for index in range(1,len(nlist)): currentvalue = nlist[index] position = index while position>0 and nlist[position-1]>currentvalue: nlist[position]=nlist[position-1] position = position-1 nlist[position]=currentvalue nlist = [14,46,43,27,57,41,45,21,70] insertionSort(nlist) print(nlist)
Insertion sort provides several advantages:
www.teachyourselfpython.com