《算法图解》笔记

 
算法的运行时间并不以秒为单位。
 算法的运行时间是其从增速的角度衡量的。
 算法的运行时间用大O表示法表示

1.二分查找输入是一个有序列表。

  

def binary_search(list1, item):
  """
  二分查找的速度比简单查找快很多。
  O(log n)比O(n)快。需要搜索的元素越多,前者就比后者快得越多。
  """
  start = 0
  end = len(list1) - 1

  while start <= end:
    middle = int((start+ end) / 2)
    guess = list1[middle]
    if guess == item:
      return middle
    elif guess > item:
      end = middle - 1
    else:
      start = middle+1
    return None
 
2.选择排序
  
def findSmallest(arr):
  smallest = arr[0]
  small_index = 0
  for i in range(1, len(arr)):
    if arr[i] < smallest:
    smallest = arr[i]
    small_index = i
  return small_index

def selectionSort(arr):
  out = []
  while arr:
  out.append(arr.pop(findSmallest(arr)))
  return out
 
3.快速排序
 
def quicksort(array):
  if len(array) < 2: 
    return array
  else: 
    pivot = array[0]
    less = [i for i in array[1:] if i < pivot]
    greater = [i for i in array[1:] if i > pivot]
    return quicksort(less) + [pivot] + quicksort(greater)
 
4.广度优先搜索
 
def search():
  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"] = []

  from collections import deque
  search_queue = deque()
  search_queue += graph["you"]

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

  while search_queue:
    person = search_queue.popleft()
    if person_is_seller(person):
      print(person+"is a mango seller")
      return True
    else:
      search_queue += graph[person]
    return False
 
5.狄克斯特拉算法
graph = {}
graph["start"] = {}
graph["start"]["a"] = 6
graph["start"]["b"] = 2

graph["a"] = {}
graph["a"]["end"] = 1

graph["b"] = {}
graph["b"]["a"] = 3
graph["b"]["end"] = 5

graph["end"] = {}

infinity = float("inf")
costs = {}
costs["a"] = 6
costs["b"] = 2
costs["end"] = infinity

parents = {}
parents["a"] = "start"
parents["b"] = "start"
parents["end"] = None

processed= []

def find_lowest_cost_node(costs):
  lowest_cost = float("inf")
  lowest_cost_node = None
  for node in costs:
    cost = costs[node]
    if cost < lowest_cost and node not in processed:
      lowest_cost = cost
      lowest_cost_node = node
  return lowest_cost_node

node = find_lowest_cost_node(costs)

while node is not None:
  nb = graph[node]
  for n in nb.keys():
    new = costs[node]+nb[n]
    if costs[n] > new:
      costs[n] = new
      parents[n] = node
  processed.append(node)
  node = find_lowest_cost_node(costs)

猜你喜欢

转载自www.cnblogs.com/thyh/p/9226944.html