Python氣泡排序演算法

2021-09-17 02:55:02 字數 2168 閱讀 3837

氣泡排序, 一種簡單的排序演算法.重複的訪問要排序數列,如果他們的順序錯誤,就把位置交換過來,直到沒有需要交換.這個演算法的由來是因為越小的元素會經由交換會慢慢的浮到數列的頂端.

冒泡演算法的運用如下:

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

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

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

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

python**如下:

# coding=utf-8

import random

class bubble:

def main(self):

arr_list = [each for each in range(10)]

random.shuffle(arr_list)

print("raw list: ", arr_list)

self.sort_arr(arr_list)

def sort_arr(self, arr):

for j in range(len(arr) - 1):

if arr[j] > arr[j + 1]:

self.swap(arr, j)

print("process list: ", arr)

self.sort_arr(arr)

@staticmethod

def swap(arr, j):

arr[j], arr[j + 1] = arr[j + 1], arr[j]

if __name__ == '__main__':

bubble = bubble()

bubble.main()

結果如下:

raw list: [4, 6, 9, 1, 2, 5, 7, 3, 0, 8]

process list: [4, 6, 1, 9, 2, 5, 7, 3, 0, 8]

process list: [4, 1, 6, 9, 2, 5, 7, 3, 0, 8]

process list: [1, 4, 6, 9, 2, 5, 7, 3, 0, 8]

process list: [1, 4, 6, 2, 9, 5, 7, 3, 0, 8]

process list: [1, 4, 2, 6, 9, 5, 7, 3, 0, 8]

process list: [1, 2, 4, 6, 9, 5, 7, 3, 0, 8]

process list: [1, 2, 4, 6, 5, 9, 7, 3, 0, 8]

process list: [1, 2, 4, 5, 6, 9, 7, 3, 0, 8]

process list: [1, 2, 4, 5, 6, 7, 9, 3, 0, 8]

process list: [1, 2, 4, 5, 6, 7, 3, 9, 0, 8]

process list: [1, 2, 4, 5, 6, 3, 7, 9, 0, 8]

process list: [1, 2, 4, 5, 3, 6, 7, 9, 0, 8]

process list: [1, 2, 4, 3, 5, 6, 7, 9, 0, 8]

process list: [1, 2, 3, 4, 5, 6, 7, 9, 0, 8]

process list: [1, 2, 3, 4, 5, 6, 7, 0, 9, 8]

process list: [1, 2, 3, 4, 5, 6, 0, 7, 9, 8]

process list: [1, 2, 3, 4, 5, 0, 6, 7, 9, 8]

process list: [1, 2, 3, 4, 0, 5, 6, 7, 9, 8]

process list: [1, 2, 3, 0, 4, 5, 6, 7, 9, 8]

process list: [1, 2, 0, 3, 4, 5, 6, 7, 9, 8]

process list: [1, 0, 2, 3, 4, 5, 6, 7, 9, 8]

process list: [0, 1, 2, 3, 4, 5, 6, 7, 9, 8]

process list: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Python排序演算法 氣泡排序

def bubblesort seq length len seq for i in range length for j in range length 1,i,1 if seq j 1 seq j seq j 1 seq j seq j seq j 1 if name main seq 2,9,...

python 排序演算法 氣泡排序

所謂氣泡排序就是 將乙個數列中的數字兩兩之間進行比較,如果第乙個元素大於或小於第二個元素,那麼就將兩個元素位置交換,然後這個小或大值再往下兩兩比較,使最大或最小值慢慢浮到數列的最頂端,這樣的排序演算法我們稱之為氣泡排序。1 首先要獲取乙個數列,或者說乙個容器,那麼len 容器 2,否則我想排序就沒有...

Python氣泡排序演算法

coding utf 8 氣泡排序演算法 import random fenshu int input 請輸入考試滿分 renshu int input 請輸入考試人數 sortsre input 倒敘 正序 請選擇 y n while sortsre y and sortsre n print 您...