- 需求:输入 n 个整数并将这些数字以从大到小和从小到大的顺序输出
- 代码如下:
- bubble_sort_v1
1 #coding:utf-8 2 #__author__ = 'Diva' 3 4 # 升序(从小到大) 5 SORT_TYPE_ASC = 1 6 # 降序(从大到小) 7 SORT_TYPE_DESC = -1 8 9 def swap(slist, ia, ib): 10 tmp = slist[ia] 11 slist[ia] = slist[ib] 12 slist[ib] = tmp 13 14 # 基本的冒泡排序 15 def sort(sort_type, sort_list): 16 i = 0 17 size = len(sort_list) 18 while i < size: 19 j = 0 20 while j < size - 1: 21 if (sort_type == SORT_TYPE_ASC and sort_list[j] > sort_list[j + 1]) or (sort_type == SORT_TYPE_DESC and sort_list[j] < sort_list[j + 1]): 22 swap(sort_list, j, j + 1 ) 23 j += 1 24 i += 1 25 26 if __name__ == '__main__': 27 mylist = [3, 5, 2, 1, 4] 28 sort(SORT_TYPE_ASC, mylist) 29 print('mylist sort as asc: %s' % (mylist)) 30 sort(SORT_TYPE_DESC, mylist) 31 print('mylist sort as desc: %s' % (mylist))
- bubble_sort_v2
1 #coding:utf-8 2 #__author__ = 'Diva' 3 4 # 升序(从小到大) 5 SORT_TYPE_ASC = 1 6 # 降序(从大到小) 7 SORT_TYPE_DESC = -1 8 9 def swap(slist, ia, ib): 10 tmp = slist[ia] 11 slist[ia] = slist[ib] 12 slist[ib] = tmp 13 14 # 优化排序次数,每轮选出当前范围数组内的极值(最大,最小),并不断减少数组范围 15 def sort_v2(sort_type, sort_list): 16 i = 0 17 size = len(sort_list) 18 while i < size: 19 t = i 20 j = i + 1 21 while j < size: 22 if(sort_type == SORT_TYPE_ASC and sort_list[t] > sort_list[j]) or (sort_type == SORT_TYPE_DESC and sort_list[t] < sort_list[j]): 23 t = j 24 j += 1 25 if t != i: 26 swap(sort_list, t, i) 27 i += 1 28 29 if __name__ == '__main__': 30 mylist = [3, 5, 2, 1, 4] 31 sort_v2(SORT_TYPE_ASC, mylist) 32 print('mylist sort as asc: %s' % (mylist)) 33 sort_v2(SORT_TYPE_DESC, mylist) 34 print('mylist sort as desc: %s' % (mylist))
- bubble_sort_v3
1 #coding:utf-8 2 #__author__ = 'Diva' 3 4 # 升序(从小到大) 5 SORT_TYPE_ASC = 1 6 # 降序(从大到小) 7 SORT_TYPE_DESC = -1 8 9 def swap(slist, ia, ib): 10 tmp = slist[ia] 11 slist[ia] = slist[ib] 12 slist[ib] = tmp 13 14 # 再次简化判断条件 15 def sort_v3(sort_type, sort_list): 16 i = 0 17 size = len(sort_list) 18 while i < size: 19 t = i 20 j = i + 1 21 while j < size: 22 #if(sort_type == SORT_TYPE_ASC and sort_list[t] > sort_list[j]) or (sort_type == SORT_TYPE_DESC and sort_list[t] < sort_list[j]): 23 if (sort_list[t] - sort_list[j]) * sort_type > 0: 24 t = j 25 j += 1 26 if t != i: 27 swap(sort_list, t, i) 28 i += 1 29 30 if __name__ == '__main__': 31 mylist = [3, 5, 2, 1, 4] 32 sort_v3(SORT_TYPE_ASC, mylist) 33 print('mylist sort as asc: %s' % (mylist)) 34 sort_v3(SORT_TYPE_DESC, mylist) 35 print('mylist sort as desc: %s' % (mylist))
- 测试结果: