众所周知,算法不仅在面试中经常问到,而且在实际的项目中更是经常用到,特整理了几个关于Python常用的算法,看代码。
chapter one :选择排序
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 = findSmallest(arr)
newArr.append(arr.pop(smallest))
return newArr
print(selectionSort([5,3,6,2,10,2]))
chapter two 快速排序
def quickSort(list):
if len(list)<=1:
return list
else:
return quickSort([i for i in list[1:]if i<list[0]])+list[0:1]+
quickSort([j for j in list[1:] if j>=list[0]])
aList=[5,3,7,6,2,10,4]
print(quickSort(aList))
chapter three 二分查找
#使用二分法的前提是有序列表
bList = [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 binary_search(number_list,x):
left,right=0,len(number_list)
while left<right:
mid=int((left+right)/2)
if number_list[mid]>x:
right=mid
elif number_list[mid]<x:
left=mid+1
else:
return '待查找元素{0}在列表下标为:{1}'.format(x,mid)
return '待查找元素%s不存在指定列表中'%x
print(binary_search(bList,22))
print(binary_search(bList,5))
print(binary_search(bList,72))
print(binary_search(bList,54))
print(binary_search(bList,30))
此方法可以给出查找目标在列表中的下标(从零开始哦)