利用python實現冒泡排序

來源:互聯網
上載者:User

標籤:enter   nbsp   print   path   port   rand   log   after   python實現   

1、先生存一個隨機數組成的list

2、然後進行排序,把大的元素放在後面,小的元素放在前面,最終實現從小到大排列

首先生存一個隨機數組成的list

import random# print(sys.path)# print(__file__)l1 = []for i in range(6):    i = random.randrange(0,165535)    l1.append(i)print(l1)[72764, 163851, 54255, 51053, 106289, 48579]

 

然後對這個列表進行排序

r = len(l1)for m in range(r-1):    a = 0    for n in range(r-1):        if l1[a] > l1[a + 1]:             tmp_before = l1[a]             tmp_after = l1[a + 1]             l1[a] = tmp_after             l1[a + 1] = tmp_before             # print(l1)        elif l1[a] == l1[a + 1]:            s = "l1[%s]和l1[%s]相等,這次不用替換" %(a,a+1)            print(s.center(40,"-"))            pass        else:            s = "l1[%s]比l1[%s]小,這次不用替換" % (a, a + 1)            print(s.center(40,"-"))            pass        a += 1print(l1)[48579, 51053, 54255, 72764, 106289, 163851]

 

利用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.