defbubble_sort(ls): # print(f"the origin list is {ls}") temp = 0 for i inrange(len(ls)-1,-1,-1): for j inrange(i): if(ls[j]>ls[j+1]): temp = ls[j] ls[j] = ls[j+1] ls[j+1] = temp # print(f"after bubble sort {ls}")
2.selection sort: O(n^2)
虽然还是O(n^2),但是比冒泡少一点swapping
1 2 3 4 5 6 7 8 9 10 11 12
defselection_sort(ls): # print(f"the origin list is {ls}") for i inrange(len(ls)-1, -1, -1): pos_biggest = 0 for j inrange(i+1): if(ls[pos_biggest]<ls[j]): pos_biggest = j if(pos_biggest!=i): temp = ls[pos_biggest] ls[pos_biggest] = ls[i] ls[i] = temp # print(f"after selection sort {ls}")
3.insertion sort: O(n^2)
1 2 3 4 5 6 7 8 9 10
definsertion_sort(ls): # print(f"the origin list is {ls}") for i inrange(1,len(ls)): temp = ls[i] j = i while(j>0and ls[i-1]>temp): ls[j] = ls[j-1] #move the bigger one back one position j = j-1 ls[j] = temp #place the temp at j(j might become smaller than i) # print(f"after insertion sort {ls}")