Python——冒泡演算法,python冒泡

來源:互聯網
上載者:User

Python——冒泡演算法,python冒泡

冒泡演算法:對於要排序的序列,每次將兩個元素進行比較,如果排序錯誤則將兩者進行交換,直到完成排序。

 
以數列 li = [12,22,3,11,8,10] 為例:

for m in range(len(li)-1):
for n in range(m+1,len(li)):
if li[m] > li[n]:
temp = li[n]
li[n] = li[m]
li[m] = temp
print li
for n in range(1,len(li)-1):
for m in range(len(li)-n):
num1 = li[m]
num2 = li[m + 1]
if num1 > num2:
temp = li[m]
li[m] = num2
li[m + 1] = temp
print li
 
兩者的區別在於,前者從前往後排序,從小的值開始排序,最後排序的是大的值;
後者是從後往前排序,從大的值開始排序,最後排序的是小的值
 
以第二種方法進行詳細分解
for m in range(5):
num1 = li[m]
num2 = li[m+1]
if num1 > num2:
temp = li[m]
li[m] = num2
li[m+1] = temp
print li

列表一共6個元素,需要比較5次,兩兩進行比較後,得到新的序列,最大的值排在最後一個。

for m in range(4):
num1 = li[m]
num2 = li[m+1]
if num1 > num2:
temp = li[m]
li[m] = num2
li[m+1] = temp
print li
再次進行迴圈,由於最後一個元素已經為最大值,只需要比較前5個,從而得到第二大的值。
以此類推,可以發現range中的值從len(li-1)開始依次減1,因此可以再套一層for迴圈。
 
for n in range(1,len(li)-1):
    #n為1,2,3,4,5
    #len(li)-n則為5,4,3,2,1
for m in range(len(li)-n):
num1 = li[m]
num2 = li[m + 1]
if num1 > num2:
temp = li[m]
li[m] = num2
li[m + 1] = temp
print li

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.