Site icon KSoftLabs

Insertion Sort Using Python

Python Tutorial by KSoftLabs.com

Read about Insertion Sort at http://interactivepython.org/runestone/static/pythonds/SortSearch/TheInsertionSort.html

def insertionSort(alist): #defining the function
   for index in range(1,len(alist)): #run through the list form element 1

     currentvalue = alist[index] #store the current value to compare
     position = index

     while position>0 and alist[position-1]>currentvalue: #move from right to left while the comparing value is less than the item in the list
         alist[position]=alist[position-1] #move the larger value to right
         position = position-1 

     alist[position]=currentvalue #if value to the left is greater than comparing value, insert the value to that position

 

 

Exit mobile version