个人有时候会把冒泡排序和选择排序搞混了,因为感觉它们之间的差别也没太大,如下是冒泡排序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次,而选择排序只交换一次。同时需要注意索引,排序里面很恶心的一点就是索引了,有时候按照伪代码来实现算法,效果不尽理想,一般很有可能也是出现在索引问题上。
来源:oschina
链接:https://my.oschina.net/u/272728/blog/227239