Bubble sort
1 defBubble_sort (LI):2 " "the complexity of this algorithm is O (n**2)" "3 forIinchRange (Len (LI)-1):#The list length is n and requires n-1 times4 " "5 the number of values for I is n-16 when i=0, the number of J values is n-17 when I=1, the number of J values is N-1-18 when i=2, the number of J values is N-1-1-19 Therefore, the number of values for I,J is n-1-Ten " " One forJinchRange (Len (LI)-1-i): A #If the subsequent number is less than the previous number, the two number is exchanged before and after - ifLI[J] > Li[j+1]: -LI[J],LI[J+1] = li[j+1],li[j] theLi = [Random.randint (0,10000) forIinchRange (10000)] - Print(LI) - Bubble_sort (LI) - Print(LI)
Select sort
#Select Sort#a trip to sort records the smallest number, put it in the first position#one more trip. Sort records record the smallest number of unordered areas and put them in the second position# ......#algorithm key: Ordered and unordered areas, the location of the smallest number of unordered#the complexity of this algorithm is O (n**2)defSelect_sort (LI): forIinchRange (Len (LI)-1): #need to arrange n-1 tripTMP = i#the index of the smallest number of unordered extents used by the TMP record forJinchRange (i+1, Len (LI)):" "When the range of J is i=0, the range of J is 1 to the last I=1, the range of J is 2 to the last ..." " ifli[j]<li[tmp]: tmp=J Li[i],li[tmp]=Li[tmp],li[i]#li = [23,35,3,23,23,2,1,4,34,23,4,3,23,5,23,2,34,23,23,2,34,2,4534,6,7,4,6,8,3,42]#li = [random.randint (0,10000) for I in range (+)]#print (Len (LI), Li)#Select_sort (LI) # spents 0.053#Print (LI)#li = [random.randint (0,10000) for I in range (10000)]#print (Len (LI), Li)#Select_sort (LI) # spents 6.057#Print (LI)
Insert Sort
The time complexity of this algorithm is also O (n**2)
1 defInsert_sort (LI):2 forIinchRange (1, Len (LI)):3TMP =Li[i]4j = I-1#J refers to the subscript of the hand5 whileJ>=0 andLI[J] >tmp:6LI[J+1] =Li[j]7J-= 18LI[J+1] =tmp9 #li = [3,2,5,6,4,3,6,7,5,7,6,45,7,8,8,34]Ten #print (Insert_sort (LI)) OneLi = [Random.randint (0,10000) forIinchRange (1000)] A Print(LI) -Insert_sort (LI)#0.049 - Print(LI)# the -Li = [Random.randint (0,10000) forIinchRange (10000)] - Print(LI) -Insert_sort (LI)#5.46 + Print(LI)#
The sorting algorithm of Python algorithm