1. 程式人生 > >使用Python完成排序

使用Python完成排序

最小值 最大值 nth () color return obj 選擇 pre

 1 class Sort(object):
 2 
 3     @staticmethod
 4     def bubble_sort(ls):
 5         lenth = len(ls)
 6         if lenth == 0:
 7             return []
 8         while lenth:
 9             for i in range(lenth-1):
10                 if ls[i] > ls[i+1]:
11                     ls[i], ls[i+1] = ls[i+1], ls[i]
12 lenth -= 1 13 return ls 14 15 @staticmethod 16 def select_sort(ls): 17 if not ls: 18 return [] 19 lenth = len(ls) 20 i = 0 21 while i < lenth-1: 22 min_v = ls[i] 23 for n in range(i+1, lenth): 24 if
ls[n] < min_v: 25 loc, min_v = n, ls[n] 26 if ls[i] != min_v: 27 ls[i], ls[loc] = ls[loc], ls[i] 28 i += 1 29 return ls 30 31 @staticmethod 32 def insert_sort(ls): 33 if not ls: 34 return [] 35 i = 1 36
lenth = len(ls) 37 while i < lenth: 38 for n in range(0, i): 39 if ls[n] > ls[n+1]: 40 ls[n], ls[n+1] = ls[n+1], ls[n] 41 i += 1 42 return ls 43 44 45 46 47 if __name__ == __main__: 48 ls = [1, 9, 5, 4, 3, 7, 6] 49 s = Sort() 50 print(s.bubble_sort(ls)) 51 print(s.select_sort(ls)) 52 print(s.insert_sort(ls))

可知:

  1. 冒泡排序是將最大值(最小值)通過相鄰交換到行尾(行首);
  2. 選擇排序是選出最大值(最小值)放到行尾(行首);
  3. 插入排序是通過相鄰交換將下一個數插入到已經排好序的序列中。

使用Python完成排序