python基础一 ------排序和查找算法
插入排序;
假设数组长度为n,先从第二个元素开始,与前一个元素比较,之后将较小的元素
放在前面,现在前两个元素是有顺序的,这时取第三个元素,与前一个元素(也就是第二个)比较,较小的放在前面
因为前面两个元素顺序已经排好,再将这个新进入到前面的较小元素与前面排好顺序的元素依次比较,直到找到合适位置插入
举例:[9,4,3,1]
顺序依次:-->[4,9,3,1]
-->[4,3,9,1]-->[3,4,9,1]
--[3,4,1,9]-->[3,1,4,9]-->[1,3,4,9]
代码
1 #-*-coding:utf-8 -*- 2 3 4 def insert_sort(lists): 5 6 print("原数据",lists) 7 num = len(lists) 8 for i in range(1,num): 9 key = lists[i] 10 j = i-1 11 while(j>=0): 12 if lists[j]>key: 13 lists[j+1] = lists[j] 14 lists[j] = key 15 print(lists) 16 j -=1 17 print("排序后",lists) 18 19 insert_sort([9,4,3,1])
冒泡排序:
1 def bubble_sort(lists): 2 print("排序前:冒泡排序",lists) 3 num = len(lists) 4 for i in range(0,num): 5 for x in range(i+1,num): 6 if(lists[x]<lists[i]): 7 temp = lists[i] 8 lists[i] = lists[x] 9 lists[x] = temp 10 print(lists) 11 print("排序后",lists)
二分法查找:
代码实现
1 def binary_search(lists,e): 2 #二分法查找(必须是对于排序后的数组) 3 right = len(lists) 4 left = 0 5 while left<=right: 6 mid = int((right+left)/2) 7 if e<lists[mid]: 8 right = mid-1 9 continue 10 if lists[mid]==e: 11 return mid 12 if lists[mid]<e: 13 left = mid+1 14 15 return "not exist" 16 17 search_list = [1, 3, 4, 6, 8, 9] 18 [print(binary_search(search_list,x)) for x in search_list]
按顺序输出每个元素小标