Input a list of elements, sort in ascending/descending order using Bubble/Insertion sort.

#example of ascending order sorting using insertion sort.
 
 
# Function for insertion sort
def insertionSort(a):

# Traversing through 1 to len(arr) using for loop
for i in range(1, len(a)):
   key = a[i]

# using below loop to Move elements of a[0..i-1], that are
# greater than key, to one position ahead
# of their current position
   j = i-1
   while j >=0 and key < a[j] :
       a[j+1] = a[j]
       j -= 1                #same as j=j-1
   a[j+1] = key         #key value assigned to next location


# start of program
a = [3,0,1,12, 11, 13, 5, 6,2]
insertionSort(a)
print ("Sorted list is:")
for i in range(len(a)):
    print(a[i]) 
 
Explanation: Insertion Sorting is like arrangement of cards in ascending or descending order in cards game. in this program we have a list named a having a list of elements. we used for loop from index position 1 here, as we go on matching from this location.
 
while loop is used inside to shift the elements to one location next, so that a empty(logically) index position for key value can be used to store. whenever we get a element greater that key value, we shift all the elements to next location in memory, so that we get memory location to store key value at comparing index position in memory.
 
This way whole list is compared and each item in list is used as key at each iteration of for loop. you can also do this from second last item of list a and running for loop in backward counting direction. try yourself now !!