python排序演算法之冒泡,選擇,插入

來源:互聯網
上載者:User

標籤:logs   algorithm   code   最大   ted   書籍   print   sorted   數字   

1.參考

一本關於排序演算法的 GitBook 線上書籍 《十大經典排序演算法》,使用 JavaScript & Python & Go 實現

2.冒泡排序:兩兩比較,互換位置
arr = [9,8,2,23,3]# 冒泡排序 兩兩比較,互換位置# 3 5 9 1 8# A B C D E# 3 5 9 1 8# 3 5 9 1 8# 3 5 1 9 8# 3 5 1 8 9# 第一輪比較將最大數排到最後,5個數總共需要4輪即1,2,3,4# 比較是arr[j] > arr[j+1],第一輪j取前4個數即range(4)即可,第二輪j取前3個數range(3)即可# 5個數總共比較 4 3 2 1 = 10次def bubble_sort(arr):    print ‘bubble_sort:‘,arr    count = 0    for i in range(1, len(arr)):        for j in range(len(arr)-i):            count += 1            if arr[j] > arr[j+1]:                arr[j], arr[j+1] = arr[j+1], arr[j]    print ‘bubble_sorted:‘, count, arrbubble_sort([9,8,2,23,3])    # bubble_sort([int(i) for i in raw_input(‘:‘).split()])   
2.選擇排序:找出極值,換到隊頭
# 3 5 9 1 8# A B C D Edef select_sort(arr):    count = 0    for i in range(len(arr)-1): #總共需要4次min or max        arr_min = min(arr[i:])  #取出的數放在列首更容易處理        arr.remove(arr_min)        arr.insert(i, arr_min)  #注意插入位置更新    print arr# select_sort(arr[:])   # 五個數字需要4輪# 0位和1,2,3,4比較,小的馬上換到0位# 1位和2,3,4比較,小的馬上換到1位def select_sort1(arr):    count = 0    for i in range(len(arr)-1):        for j in range(i+1, len(arr)):            count += 1            if arr[i] > arr[j]:  #注意arr[i]一直被更新                arr[i], arr[j] = arr[j], arr[i]    print count    print arr# select_sort1(arr[:])   def select_sort2(arr):    print ‘select_sort2:‘,arr    count = 0    for i in range(len(arr)-1):        min_index = i        for j in range(i+1, len(arr)):            count += 1            if arr[min_index] > arr[j]:                min_index = j        arr[i], arr[min_index] = arr[min_index], arr[i]  #一輪之後再更新 arr[i]    print ‘select_sort2ed:‘, count, arrselect_sort2([9,8,2,23,3])  
3.插入排序:打牌,已排+未排,逐個插入(折半最佳化)
# 3 5 9 1 8# A B C D E#A已排序,BCDE未排序#AB已排序,CDE未排序def insert_sort(arr):    print ‘insert_sort:‘,arr    count = 0    for i in range(1, len(arr)):  #運算元是B        for j in range(0,i):  #運算元是A            count += 1            print ‘B‘, arr[i], ‘A‘, arr[j], arr            if arr[i] < arr[j]:                arr.insert(j, arr[i])                  arr.pop(i+1)  #先插入,導致原來要移除的位置推後1位                print arr                break    print ‘insert_sorted:‘, count, arrinsert_sort([9,8,2,23,3]) 

 

python排序演算法之冒泡,選擇,插入

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.