python實現冒泡排序

來源:互聯網
上載者:User
python演算法 - python實現冒泡排序

冒泡排序的運算原理:

比較相鄰的元素。如果第一個比第二個大,就交換他們兩個。

對每一對相鄰元素作同樣的工作,從開始第一對到結尾的最後一對。在這一點,最後的元素應該會是最大的數。

針對所有的元素重複以上的步驟,除了最後一個。

持續每次對越來越少的元素重複上面的步驟,直到沒有任何一對數字需要比較。


執行個體代碼

# -*- encoding: utf-8 -*-


def bubble_sort(seq, cmp=cmp):

"""冒泡排序,偽碼如下:

BUBBLESORT(A)

1 for i ← 1 to length[A]

2 do for j ← length[A] downto i+1

3 do if A[j] < A[j-1]

4 then exchange A[j] A[j-1]


T(n) = θ(n^2)


Args:

seq (Sequence): 一個序列對象。

cmp (Function): 比較函數。預設為內建函數cmp()。


Returns:

一個排序後的列表。

"""

if (seq == None):

return None

length = len(seq)


for i in range(length):

for j in range(length-1, i, -1):

if seq[j] < seq[j-1]:

seq[j], seq[j-1] = seq[j-1], seq[j]


return seq


if __name__ == '__main__':

import random, timeit


items = range(10000)

random.shuffle(items)


def test_sorted():

print(items)

sorted_items = sorted(items)

print(sorted_items)


def test_bubble_sort():

print(items)

sorted_items = bubble_sort(items)

print(sorted_items)


test_methods = [test_sorted, test_bubble_sort]

for test in test_methods:

name = test.__name__ # test.func_name

t = timeit.Timer(name + '()', 'from __main__ import ' + name)

print(name + ' takes time : %f' % t.timeit(1))

  • 聯繫我們

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