2. Iterative Insertion Sort

!500
Outer loop: for loop
for loop to check each element
Inner loop: while loop
conditional while loop to find the correct element position
def insertionSort(array):
for i in range(1, len(array)):
j=i
while j>0 and array[j]<array[j-1]:
#while element index(2) larger than zero
#while second element is smaller than first element and
array[j-1],array[j]=array[j],array[j-1]
j-=1#1-1=0# second element is sorted
return array
every index is sorted to its left most(ascending order) position before the index is incremented to sort the next index
-
making sure a list of [5,1,6,2,4,3], an index of [0,1,2,3,4,5] the 1(index 1) will always be sorted to left most first
-
every iteration inside while loop, make sure the index will be at its left most position in the list
-
focus on fixed index element movement
-
outer loop makes sure every index is iterated so that the full list will have ascending order
after each outer loop, the next index is check
inner loop until the index is at its smallest position