Python code:
"""Insert Sort (1) Insert unsorted number one by one into sorted array"""LST= [3, 6, 9, 1, 4, 7, 2, 8, 5, 0]Print("before sorting:%s\r\n"%lst)#Wheel forIinchRange (1,len (LST)):#unsorted Array Print("section%s round"%i)#Times forJinchRange (i):#sorted Array (initial assumption first number sorted) ifLst[i] <=Lst[j]:Print("comparison [%s]:%s [%s]:%s, need to insert"%(i, Lst[i], J, Lst[j])) Lst.insert (J, Lst[i]) lst.pop (i+1) Print("after insertion:%s"%lst) Break Else: Print("comparison [%s]:%s [%s]:%s, not inserted"%(i, Lst[i], J, Lst[j]))Print("\ r \ n Sort after:%s"% LST)
Output Result:
E:\python\algorithm>Python3 insertsort.py before sorting: [3, 6, 9, 1, 4, 7, 2, 8, 5, 0] 1th round comparison [1]:6 [0]:3, without inserting a 2nd round comparison [2]:9 [0]:3, do not insert comparison [2]:9 [1]:6, without inserting a 3rd round comparison [3]:1 [0]:3, insert after insert: [1, 3, 6, 9, 4, 7, 2, 8, 5, 0] 4th round comparison [4]:4 [0]:1, do not insert comparison [4]:4 [1]:3, do not insert comparison [4]:4 [2]:6, insert after insert: [1, 3, 4, 6, 9, 7, 2, 8, 5, 0] 5th round comparison [5]:7 [0]:1, do not insert comparison [5]:7 [1]:3, do not insert comparison [5]:7 [2]:4, do not insert comparison [5]:7 [3]:6, do not insert comparison [5]:7 [4]:9, insert after insert: [1, 3, 4, 6, 7, 9, 2, 8, 5, 0] 6th round comparison [6]:2 [0]:1, do not insert comparison [6]:2 [1]:3, insert after insert: [1, 2, 3, 4, 6, 7, 9, 8, 5, 0] 7th round comparison [7]:8 [0]:1, do not insert comparison [7]:8 [1]:2, do not insert comparison [7]:8 [2]:3, do not insert comparison [7]:8 [3]:4, do not insert comparison [7]:8 [4]:6, do not insert comparison [7]:8 [5]:7, do not insert comparison [7]:8 [6]:9, insert after insert: [1, 2, 3, 4, 6, 7, 8, 9, 5, 0] 8th round comparison [8]:5 [0]:1, do not insert comparison [8]:5 [1]:2, do not insert comparison [8]:5 [2]:3, do not insert comparison [8]:5 [3]:4, do not insert comparison [8]:5 [4]:6, insert after insert: [1, 2, 3, 4, 5, 6, 7, 8, 9, 0] 9th round comparison [9]:0 [0]:1, insert after insertion: [0,1, 2, 3, 4, 5, 6, 7, 8, 9] After sorting: [0,1, 2, 3, 4, 5, 6, 7, 8, 9]
===== End =====
Insertion Sort (1)