python二分查找算法/冒泡排序,及快速排序
二分查找算法
l = [2,3,5,10,15,16,18,22,26,30,32,35,41,42,43,55,56,66,67,69,72,76,82,83,88]
你观察这个列表,这是不是一个从小到大排序的有序列表呀?
如果这样,假如我要找的数比列表中间的数还大,是不是我直接在列表的后半边找就行了?
这就是二分查找算法!
那么落实到代码上我们应该怎么实现呢?
二分法
l = [2,3,5,10,15,16,18,22,26,30,32,35,41,42,43,55,56,66,67,69,72,76,82,83,88]
def func(num_list,aim,start=0,end=None):
end=len(num_list)-1 if end is None else end
print(end)
mid_index=(end-start)//2+start
print(mid_index)
if start <= end:
if num_list[mid_index] > aim:
func(num_list,aim,start=start,end=mid_index-1)
elif num_list[mid_index] < aim:
func(num_list,aim,start=mid_index+1,end=end)
else:
print('找到了{},下标为{},从左数第{}个数'.format(aim,mid_index,mid_index+1))
else:
print('不存在')
func(l,72,0,)
二分法
def search(num,l,start=None,end=None):
start = start if start else 0
end = end if end is not None else len(l) - 1
mid = (end - start)//2 + start
if start > end:
return None
elif l[mid] > num :
return search(num,l,start,mid-1)
elif l[mid] < num:
return search(num,l,mid+1,end)
elif l[mid] == num:
return mid
l = [2,3,5,10,15,16,18,22,26,30,32,35,41,42,43,55,56,66,67,69,72,76,82,83,88]
print(search(55,l,))
冒泡排序
#冒泡排序 def sort_maopao(num_list): #开始排序 for i in range(len(num_list)): for j in range(i,len(num_list)): if num_list[i]>num_list[j]: num_list[i],num_list[j]=num_list[j],num_list[i] return num_list
快速排序
def quick_sort(num_list): if not num_list or len(num_list)<=1: return num_list mid=num_list[0] left=quick_sort([i for i in num_list[1:] if i < mid]) right=quick_sort([i for i in num_list[1:] if i >=mid]) return left+[mid]+right