Python 冒泡,選擇,插入排序使用執行個體

來源:互聯網
上載者:User
最近學習了python基礎,寫一下3大排序練練手:

複製代碼 代碼如下:


'''
Created on 2013-8-23
@author: codegeek
'''
//冒泡排序
def bubble_sort(seq):
for i in range(len(seq)):
for j in range(i,len(seq)):
if seq[j] < seq[i]:
tmp = seq[j]
seq[j] = seq[i]
seq[i] = tmp
//選擇排序
def selection_sort(seq):
for i in range(len(seq)):
position = i
for j in range(i,len(seq)):
if seq[position] > seq[j]:
position = j
if position != i:
tmp = seq[position]
seq[position] = seq[i]
seq[i] = tmp
//插入排序
def insertion_sort(seq):
if len(seq) > 1:
for i in range(1,len(seq)):
while i > 0 and seq[i] < seq[i-1]:
tmp = seq[i]
seq[i] = seq[i-1]
seq[i-1] = tmp
i = i - 1
//
if __name__ == "__main__":
print "--------bubble_sort-------------"
seq = [22,1,33,4,7,6,8,9,11]
bubble_sort(seq)
print seq
print "--------selection_sort-------------"
seq = [88,44,33,4,7,6,8,9,11]
selection_sort(seq)
print seq
print "--------insertion_sort-------------"
seq = [777,44,33,4,7,6,1111,100,11]
insertion_sort(seq)
print seq

以上就是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.