# 几种常见算法的Python实现

## 1、选择排序

#找到最小的元素
def FindSmall(list):
min=list[0]
for i in range(len(list)):
if list[i]<min:
min=list[i]
return min

#选择排序
def Select_Sort(list):
newArr=[]
for i in range(len(list)):
minValue=FindSmall(list)
newArr.append(minValue)
list.remove(minValue)
return newArr

testArr=[11,22,33,21,123]
print(Select_Sort(testArr))

## 2、快速排序

def Quick_Sort(list):
if len(list)<2:
return list
else:
temp=list[0]
less=[i for i in list[1:] if i<=temp]
more=[i for i in list[1:] if i>temp]
return Quick_Sort(less)+[temp]+Quick_Sort(more)

testArr= [13,44,53,24,876,2]
print(Quick_Sort(testArr)) 

## 3、二分查找

def Item_Search(list,item):
low=0
high=len(list)-1
while low<=high:
middle=(low+high)//2
print(list[middle])
if list[middle]>item:
high=middle-1
elif list[middle]<item:
low=middle+1
else:
return middle
return None

test_list=[1,3,5,7,9,11,13,15,17,19,21]
Item_Search(test_list,11)   

## 4、广度优先搜索

#使用字典构建图
graph={}
graph["you"]=["Alice","Bob","Claire"]
graph["Bob"]=["Anuj","Peggy"]
graph["Alice"]=["Peggy"]
graph["Claire"]=["Tom","Jonny"]
graph["Anuj"]=[]
graph["Peggy"]=[]
graph["Tom"]=[]
graph["Jonny"]=[]

from collections import deque

#简单的判断方法
def person_is_seller(name):
return name=='Tom'

def Search(name):
searched=[]   #用于记录检查过的人，防止进入死循环
search_queue=deque()  #创建队列
search_queue+=graph[name]
while search_queue:
person=search_queue.popleft()
if not person in searched:    #仅当这个人没检查过时才检查
if person_is_seller(person):
print("the seller is {0}".format(person))
return True
else:
search_queue+=graph[person]
searched.append(person)   #将这个人标记为检查过
return False

print(Search("you"))

## 5、贪婪算法

fruits=set(["苹果","香蕉","梨子","西瓜","草莓","橘子","荔枝","榴莲"])

#箱子以及包含的水果
box={}
box["b1"]=set(["苹果","香蕉","西瓜"])
box["b2"]=set(["草莓","橘子","榴莲"])
box["b3"]=set(["梨子","荔枝","草莓"])
box["b4"]=set(["香蕉","橘子"])
box["b5"]=set(["梨子","榴莲"])

final_boxs=set() #最终选择的箱子

#直到fruits为空
while fruits:
best_box=None  #包含了最多的未包含水果的箱子
fruits_covered=set()  #包含该箱子包含的所有未包含的水果

#循环迭代每个箱子，并确定它是否为最佳箱子
for boxItem,fruitItem in box.items():
covered=fruits & fruitItem  #计算交集
if len(covered)>len(fruits_covered):
best_box=boxItem
fruits_covered=covered
fruits-=fruits_covered
print(final_boxs)