- class Sort(object):
- @staticmethod
- def bubble_sort(ls):
- lenth = len(ls)
- if lenth == 0:
- return []
- while lenth:
- for i in range(lenth-1):
- if ls[i]> ls[i+1]:
- ls[i], ls[i+1] = ls[i+1], ls[i]
- lenth -= 1
- return ls
- @staticmethod
- def select_sort(ls):
- if not ls:
- return []
- lenth = len(ls)
- i = 0
- while i <lenth-1:
- min_v = ls[i]
- for n in range(i+1, lenth):
- if ls[n] < min_v:
- loc, min_v = n, ls[n]
- if ls[i] != min_v:
- ls[i], ls[loc] = ls[loc], ls[i]
- i += 1
- return ls
- @staticmethod
- def insert_sort(ls):
- if not ls:
- return []
- i = 1
- lenth = len(ls)
- while i < lenth:
- for n in range(0, i):
- if ls[n]> ls[n+1]:
- ls[n], ls[n+1] = ls[n+1], ls[n]
- i += 1
- return ls
- if __name__ == '__main__':
- ls = [1, 9, 5, 4, 3, 7, 6]
- s = Sort()
- print(s.bubble_sort(ls))
- print(s.select_sort(ls))
- print(s.insert_sort(ls))
可知:
冒泡排序是将最大值 (最小值) 通过相邻交换到行尾(行首);
选择排序是选出最大值 (最小值) 放到行尾(行首);
插入排序是通过相邻交换将下一个数插入到已经排好序的序列中.
来源: http://www.bubuko.com/infodetail-2558773.html