冒泡排序:(bubble sort)
1 import time 2 def bubble_sort(a_list): 3 n = len(a_list) 4 for j in range(0,n-1):
count = 0 5 for i in range(0,n-1-j): 6 if(a_list[i]>a_list[i+1]): 7 a_list[i],a_list[i+1] = a_list[i+1],a_list[i]
count += 1
if count == 0:
return
8 print(a_list) 9 if __name__==‘__main__‘: 10 start_time = time.clock() 11 a_list = [12,35,15,6,4,8,48,54,21,65,45] 12 print(a_list) 13 bubble_sort(a_list) 14 end_time = time.clock() 15 use_time = end_time-start_time 16 print(use_time)
1 [12, 35, 15, 6, 4, 8, 48, 54, 21, 65, 45] 2 [4, 6, 8, 12, 15, 21, 35, 45, 48, 54, 65] 3 4.2666704592626304e-05
选择排序(select sort):
1 def select_sort (a_list): 2 n = len(a_list) 3 for j in range(0,n-1): 4 min = j 5 for i in range(j+1, n): 6 if a_list[min]>a_list[i]: 7 min = i 8 a_list[j] , a_list[min] = a_list[min],a_list[j] 9 print(a_list) 10 if __name__ and ‘__main__‘: 11 a_list= [12, 35, 15, 6, 4, 8, 48, 54, 21, 65, 45] 12 print(a_list) 13 select_sort(a_list)
1 [12, 35, 15, 6, 4, 8, 48, 54, 21, 65, 45] 2 [4, 6, 8, 12, 15, 21, 35, 45, 48, 54, 65]