1、二分查找
'''时有序列表
时间复杂度(x):log n #2**x =n
比如128个数字只需要查找7次,速度最快
算法:
每次都查找中间位置的元素,如果相等则返回
如果中间位置元素小于要查找的元素,则需要查找的元素在右边,更新最小位置low
如果中间位置元素大于要查找的元素,则需要查找的元素在左边,更新最大位置hign'''
#coding=utf-8
def binary_search(list,item):
low=0
high=len(list)-1
while low<=high:
mid=(low+high)//2#注意:如果是python3需要地板除,pyhton2直接除就可以
guess=list[mid]
if guess ==item:
return mid
elif guess>item:
high=mid-1
elif guess <item:
low=mid+1
number_list=list(range(1000))
print(binary_search(number_list,999))
def binary_search(list,item):
low=0
high=len(list)-115
while low<=high:
mid=(low+high)//2
guess=list[mid]
if guess ==item:
return mid
elif guess > item:
high=mid-1
elif guess<item:
low=mid+1
number_list=list(range(1000))
print(binary_search(number_list),999))
2、选择排序
选择排序的时间复杂度 n*log n,速度比二分查找慢
比如有4个元素的列表,时间复杂度位 4*log4=4*2=8
每次在当前列表查找最小元素,需要查找4轮
算法:
1、定义个查找最小元素的函数
2、遍历n次(n=数组长度),每次找出当前列表的最小元素放入一个新的列表,原列表最小元素
方法一:
#ecdoing=utf-8
def findSmallest(arr):
smallest=arr[0]
smallest_index=0
for i in range(1,len(arr)):
if arr[i]<smallest:
smallest=arr[i]
smallest_index=i
return smallest_index
def selectionSort(arr):
newArr=[]
for i in range(len(arr)):
smallest_index=findSmallest(arr)
newArr.append(arr.pop(smallest_index))
return newArr
l=[4,89,234,6546,7657,90.5]
print(selectionSort(l))
执行结果:
>>> l=[4,89,234,6546,7657,90.5]
>>> print(selectionSort(l))
[4, 89, 90.5, 234, 6546, 7657]
>>>
方法二:
双层遍历
def selectionSort(arr):
newArr=[]
tempArr=arr
for i in range(len(arr)):
smallest=tempArr[0]
for j in range(len(tempArr)):
if tempArr[j] <smallest:
smallest=tempArr[j]
newArr.append(smallest)
tempArr.remove(smallest)
return newArr
l = [4, 89, 234, 6546, 7657, 90.5]
print(selectionSort(l))
执行结果:
>>> print(selectionSort(l))
[4, 89, 90.5, 234, 6546, 7657]
方法三:
双层遍历
#encoding=utf-8
def selectionSort(arr):
newArr=[]
tempArr=arr
for i in range(len(arr)):
samll_index=0
smallest=tempArr[0]
for j in range(len(tempArr)):
if tempArr[j]<smallest:
samll_index=j
newArr.append(tempArr.pop(samll_index))
return newArr
l = [4, 89, 234, 6546, 7657, 90.5]
print(selectionSort(l))