排序算法 之 冒泡排序 BubbleSort

介紹

冒泡排序的原理非常簡單,它重複地走訪過要排序的數列,一次比較兩個元素,如果他們的順序錯誤就把他們交換過來。

步驟

  • 比較相鄰的元素。如果第一個比第二個大,就交換他們兩個。
  • 對第0個到第n-1個數據做同樣的工作。這時,最大的數就“浮”到了數組最後的位置上。
  • 針對所有的元素重複以上的步驟,除了最後一個。
  • 持續每次對越來越少的元素重複上面的步驟,直到沒有任何一對數字需要比較。

這裏寫圖片描述

這裏寫圖片描述

代碼

# -*- coding: utf-8 -*-
"""
Created on Tue Apr 26 16:41:35 2016

@author: zang
"""
from matplotlib import pyplot as plt
import random

def bubbleSort1(unsortedList):#採用遞歸
    if len(unsortedList)<2:
        return unsortedList

    list_length=len(unsortedList)
    for i in range(list_length - 1):
        if unsortedList[i] > unsortedList[i + 1]:
            unsortedList[i],unsortedList[i + 1] = unsortedList[i + 1], unsortedList[i]
    max_num = unsortedList.pop() 
    return bubbleSort1(unsortedList) + [max_num]  

def bubbleSort(unsortedList):
    if len(unsortedList)<2:
        return unsortedList

    list_length=len(unsortedList)  
    for i in range(list_length - 1):  
        for j in range(list_length - i - 1):  
            if unsortedList[j] > unsortedList[j+1]:  
                unsortedList[j],unsortedList[j+1] = unsortedList[j+1],unsortedList[j]  
    return unsortedList  

def plotScatter(inputList):
    plt.scatter(range(len(inputList)),inputList)
    plt.show()

if __name__ == "__main__":
    num_list = range(1000)
    unsortedList = random.sample(num_list, 5)
    print "unsortedList:"
    plotScatter(unsortedList)
    print unsortedList
    sortedList = bubbleSort(unsortedList)
    print "sortedList:"
    plotScatter(sortedList)
    print sortedList

    sortedList = bubbleSort1(unsortedList)
    print "sortedList1:"
    plotScatter(sortedList)
    print sortedList

測試

輸入:

[729, 114, 934, 151, 917, 262, 445, 298, 261, 259, 393, 431, 441, 331, 849, 167, 247, 686, 146, 558, 173, 744, 353, 538, 425, 271, 100, 196, 67, 819]

這裏寫圖片描述

輸出:

[67, 100, 114, 146, 151, 167, 173, 196, 247, 259, 261, 262, 271, 298, 331, 353, 393, 425, 431, 441, 445, 538, 558, 686, 729, 744, 819, 849, 917, 934]

這裏寫圖片描述

分析

情況 性能
Worst case performance: O(n2)
Best case performance: O(n)
Average case performance: O(n2)
Worst case space complexity: O(1)

優化

優化1:某一趟遍歷如果沒有數據交換,則說明已經排好序了,因此不用再進行迭代了。用一個標記記錄這個狀態即可。
優化2:記錄某次遍歷時最後發生數據交換的位置,這個位置之後的數據顯然已經有序,不用再排序了。因此通過記錄最後發生數據交換的位置就可以確定下次循環的範圍了。

參考

發佈了126 篇原創文章 · 獲贊 94 · 訪問量 46萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章