用python實現插入排序和冒泡排序

插入排序和冒泡排序的概念我就不解釋了吧spa

。。。插入排序代碼:code

複製代碼
 1 if __name__ =='__main__':
 2     l = [4,1,9,13,34,26,10,7,4]
 3 
 4 #=========================insert_sort=========================
 5     def insert_sort(l):
 6         for i in range(len(l)):
 7             min_index = i
 8             for j in range(i+1,len(l)):
 9                 if l[min_index] > l[j]:
10                     min_index = j
11             tmp = l[i]
12             l[i] = l[min_index]
13             l[min_index] = tmp
14             print(str(l))
15         print("result: " + str(l))
16 
17     insert_sort(l)
18     print("insert_sort success!!!")
複製代碼

每次遍歷,先假設list[min_index]處的值最小,再跟後面的值依次比較,當發現list[j]比list[min_index]值小時,這時的min_index替換爲j,再跟後面的進行比較,指導找到最小的那個list[j],將j付給min_index,這時l[min_index]就是遍歷過程當中的最小值了,不知道說清楚了沒~~blog

結果以下:排序

複製代碼
[1, 4, 9, 13, 34, 26, 10, 7, 4]
[1, 4, 9, 13, 34, 26, 10, 7, 4]
[1, 4, 4, 13, 34, 26, 10, 7, 9]
[1, 4, 4, 7, 34, 26, 10, 13, 9]
[1, 4, 4, 7, 9, 26, 10, 13, 34]
[1, 4, 4, 7, 9, 10, 26, 13, 34]
[1, 4, 4, 7, 9, 10, 13, 26, 34]
[1, 4, 4, 7, 9, 10, 13, 26, 34]
[1, 4, 4, 7, 9, 10, 13, 26, 34]
result: [1, 4, 4, 7, 9, 10, 13, 26, 34]
insert_sort success!!!
複製代碼

 

下面再來看冒泡排序it

複製代碼
 1 #==========================bubble_sort========================
 2 
 3     def bubble_sort(l):
 4         for i in range(len(l),0,-1):
 5             for j in range(len(l)-1):
 6                 if l[j] > l[j+1]:
 7                     tmp = l[j]
 8                     l[j] = l[j+1]
 9                     l[j+1] = tmp
10 
11         print("result: " + str(l))
12 
13     bubble_sort(l)
14     print("bubble_sort success!!!")
複製代碼

不解釋了。。class

相關文章
相關標籤/搜索