我的有时候会把冒泡排序和选择排序搞混了,由于感受它们之间的差异也没太大,以下是冒泡排序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