First, bubble sort
A, bubble sorting----optimization
If a trip is performed in a bubbling sort without swapping, the list is already ordered and can be settled directly
ImportRandom fromTimewrapImport*@cal_timedefBubble_sort (LI): forIinchRange (Len (LI)-1): #I means the number of trips #Part I: Unordered zone: (0,len (LI)-i) forJinchRange (0, Len (LI)-i-1): ifLI[J] > Li[j+1]: li[j], li[j+1] = li[j+1], Li[j] @cal_timedefBubble_sort_2 (LI):#Bubble Sort Optimization forIinchRange (Len (LI)-1): #I means the number of trips #Part I: Unordered zone: (0,len (LI)-i)Change =False forJinchRange (0, Len (LI)-i-1): ifLI[J] > Li[j+1]: li[j], li[j+1] = li[j+1], li[j] change=Trueif notChange :returnLi= List (Range (10000))#Random.shuffle (LI)#Print (LI)bubble_sort_2 (LI)Print(LI)
Second, choose the sort
A, a trip to the minimum number of traversal records, put in the first position;
b, the smallest number in the remaining list of traversed records, continue to place
ImportRandom fromTimewrapImport*@cal_timedefSelect_sort (LI): forIinchRange (Len (LI)-1): #I represents the number of times, and also indicates where the unordered zone begins.Min_loc = i#the location of the minimum number forJinchRange (i + 1, Len (LI)):ifLI[J] <Li[min_loc]: Min_loc=J Li[i], Li[min_loc]=Li[min_loc], Li[i]li= List (Range (10000)) Random.shuffle (LI)Print(LI) select_sort (LI)Print(LI)
Third, insert sort
A, the list is divided into ordered and unordered areas two parts, initially ordered area only one element
b, each time you select an element from the unordered area, insert it into a position in the ordered area until the unordered area becomes empty
ImportRandom fromTimewrapImport*@cal_timedefInsert_sort (LI): forIinchRange (1, Len (LI)):#I denotes the first number of unordered areasTMP = Li[i]#Touch the cardj = I-1#J points to the last position of the ordered area whileLI[J] > tmp andJ >=0:#cyclic termination Condition: 1. li[j] <= tmp; 2. J = =-1LI[J+1] =Li[j] J-= 1li[j+1] =Tmpli= List (Range (10000)) Random.shuffle (LI)Print(LI) insert_sort (LI)Print(LI)
Python's algorithm LOB trio