算法练习 0x0 二分查找、选择排序、快速排序、广度优先搜索

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/funkstill/article/details/88732334

二分查找

def binary_search(list,item):
    low = 0
    high = len(list)-1
    while low <= high:
        mid = (low+high)/2
        guess = list[mid]
        if guess == item:
            return mid
        if guess >item:
            high =mid-1
        else:
            low = mid+1
    return None
my_list = [1,3,5,7,9]
print binary_search(my_list,3)
print binary_search(my_list,-1)

 选择排序

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,8,7,2,1,9])

快速排序

# coding=UTF-8
def quicksort(arr):
    if len(arr)<2:#基线条件,为空或只有一个元素的数组是有序的
        return arr
    else:
        pivot = arr[0] #递归条件
        less = [i for i in arr[1:] if i<=pivot]
        greater = [i for i in arr[1:] if i>pivot]
        return quicksort(less)+[pivot]+quicksort(greater)
print quicksort([10,3,4,5])

广度优先搜索(队列实现)

# coding=UTF-8
from collections import deque

'''使用散列表存储任务关系信息'''
graph = {}
graph["you"] = ["alice","bob","claire"]
graph["bob"] = ["anuj","peggy"]
graph["alice"] = ["peggy"]
graph["claire"] = ["thom","jonny"]
graph["anuj"] = []
graph["peggy"] = []
graph["thom"] = []
graph["jonny"] = []

def search(name):
    # 使用deque创建双端队列
    search_queue = deque()
    search_queue += graph[name]  # 将你的邻居加入队列
    searched = [] #记录已经检查过的人
    while search_queue:
        person = search_queue.popleft()
        if person not in searched:
            if person_is_seller(person):
                print person + " is a mango seller!"
                return True
            else:
                search_queue += graph[person]  # 检查这个人的邻居
                searched.append(person) #记录检查过的人
    return False

def person_is_seller(name):
    return name[-1] == 'm'

search("you")

 

猜你喜欢

转载自blog.csdn.net/funkstill/article/details/88732334