Python之冒泡排序和選擇排序的比較

     我的有時候會把冒泡排序和選擇排序搞混了,由於感受它們之間的差異也沒太大,以下是冒泡排序Python的代碼:python

class BubbleSort:
    def __init__(self):
        self.initArr()
    def initArr(self):
        self.arrInfo = [60, 61, 27, 91, 92, 44, 13, 20, 24, 14]
    def bubbleSortFromStartToEnd(self):
        length = len(self.arrInfo)
        for i in range(length):
            for j in range(length-i-1):
                if self.arrInfo[j] > self.arrInfo[j+1]:
                    tmp = self.arrInfo[j]
                    self.arrInfo[j] = self.arrInfo[j+1]
                    self.arrInfo[j+1] = tmp
    def bubbleSortFromEndToStart(self):
        length = len(self.arrInfo)
        for i in range(0,length):
            for j in range(length-1,i,-1):
                if self.arrInfo[j] < self.arrInfo[j-1]:
                    tmp = self.arrInfo[j]
                    self.arrInfo[j] = self.arrInfo[j-1]
                    self.arrInfo[j-1] = tmp
    def printResult(self):
        print self.arrInfo
        self.bubbleSortFromEndToStart()
        print self.arrInfo
BubbleSort().printResult()

    以下是選擇排序Python的代碼:算法

class SelectSort:
    def __init__(self):
        self.initArr()
    def initArr(self):
        self.arrInfo = [60, 61, 27, 91, 92, 44, 13, 20, 24, 14]
    def selectSort(self):
        length = len(self.arrInfo)
        for i in range(length):
            position = i
            for j in range(i,length):
                if self.arrInfo[position] > self.arrInfo[j]:
                    position = j
            tmp = self.arrInfo[i]
            self.arrInfo[i] = self.arrInfo[position]
            self.arrInfo[position] = tmp
    def printResult(self):
        print self.arrInfo
        self.selectSort()
        print self.arrInfo
SelectSort().printResult()


    冒泡排序主要看bubbleSortFromEndToStart方法,該方法的效果和選擇排序相似,惟一的區別是冒泡排序交換0~n-1次,而選擇排序只交換一次。同時須要注意索引,排序裏面很噁心的一點就是索引了,有時候按照僞代碼來實現算法,效果不盡理想,通常頗有可能也是出如今索引問題上。code

相關文章
相關標籤/搜索