一、二分查找
1 def binary(binary_para, search): 2 bi = int(len(binary_para)/2) 3 if search == binary_para[0]: 4 print('数存在,并存在在列表第一位') 5 elif len(binary_para)>1: 6 if binary_para[bi] > search: 7 print('分段值(前):',binary_para[bi]) 8 binary(binary_para[:bi],search) 9 elif binary_para[bi] < search: 10 print('分段值(后):',binary_para[bi]) 11 binary(binary_para[bi:],search) 12 else: 13 print('你寻找的数存在列表里') 14 else: 15 print('列表里不存在你寻找的数') 16 17 if __name__ == '__main__': 18 li = list(range(8,30000,10)) 19 binary(li, 12138)
二、冒泡排序
1 def bub_sort(sort_list): 2 for i in range(len(sort_list)-2): 3 for j in range(len(sort_list)-i-1): 4 if sort_list[j]>sort_list[j+1]: 5 temp = sort_list[j+1] 6 sort_list[j+1] = sort_list[j] 7 sort_list[j] = temp 8 9 10 if __name__ == '__main__': 11 li = [65, 1, 45, 77, 3, 9, 43, 23, 7, 53, 213, 10] 12 bub_sort(li) 13 print(li)
三、选择排序
1 def select_sort(list_sort): 2 for i in range(len(list_sort)): 3 min_index = i 4 for j in range(i, len(list_sort)): 5 if list_sort[min_index] > list_sort[j]: 6 min_index = j 7 temp = list_sort[i] 8 list_sort[i] = list_sort[min_index] 9 list_sort[min_index]=temp 10 11 if __name__ == '__main__': 12 li = [65, 1, 45, 77, 3, 9, 43, 23, 7, 53, 213, 10] 13 select_sort(li) 14 print(li)
四、插入排序
1 def insert_sort(sort_list): 2 for i in range(1,len(sort_list)): 3 insert_index = i # 索引当做类似指针的使用 4 insert_value = sort_list[i] # 把要插入的值存下来,以免后面被覆盖 5 while insert_index > 0 and insert_value < sort_list[insert_index-1]: 6 sort_list[insert_index] = sort_list[insert_index-1] 7 insert_index -=1 8 sort_list[insert_index] = insert_value 9 10 if __name__ == '__main__': 11 li = [65, 1, 45, 77, 3, 9, 43, 23, 7, 53, 213, 10] 12 insert_sort(li) 13 print(li) 14
五、快速排序
图片来源:https://www.jianshu.com/p/5f38dd54b11f
1 def quick_sort(list_sort,start,end): 2 if start >= end: 3 return 4 start_index = list_sort[start] 5 left_flag = start 6 right_flag = end 7 8 while left_flag < right_flag: 9 10 while left_flag < right_flag and start_index <= list_sort[right_flag]: 11 right_flag -=1 12 list_sort[left_flag] = list_sort[right_flag] 13 14 while left_flag < right_flag and start_index >= list_sort[left_flag]: 15 left_flag += 1 16 list_sort[right_flag] = list_sort[left_flag] 17 18 list_sort[left_flag] = start_index 19 quick(list_sort, start, end, left_flag) # 递归调用 20 21 def quick(list_sort,start,end,left_flag): 22 quick_sort(list_sort,start,left_flag-1) 23 quick_sort(list_sort,left_flag+1,end) 24 25 if __name__ == '__main__': 26 li = [64, 77, 67, 8, 6, 84, 55, 20, 43, 67, 67] 27 quick_sort(li, 0, len(li) - 1) 28 print(li)