常见的5种算法运行时间
O(log n),也叫对数时间,这样的算法包括二分查找。
O(n),也叫线性时间,这样的算法包括简单查找。
O(n * log n),这样的算法包括第4章将介绍的快速排序——一种速度较快的排序算法。
O(n2),这样的算法包括第2章将介绍的选择排序——一种速度较慢的排序算法。
O(n!),这样的算法包括接下来将介绍的旅行商问题的解决方案——一种非常慢的算法。
选择排序算法
先找出一个数组里面的最小值,删除掉后继续寻找。
def findsmallest(arr):
smalldata=arr[0]
smallest_index = 0
for i in range(1,len(arr)):
if arr[i]<smalldata:
smalldata=arr[i]
smallest_index = i #########
return smallest_index
def selectionsort(arr):
selctionlist=[]
for i in range(len(arr)):
smallindex=findsmallest(arr)
selectionlist.append(arr.pop(smallindex))##########pop的是索引
return selctionlist
快速排序
使用递归方式,复杂度为n logn
def quiksort(arr):
base_data=arr[0]
lower_data=[i for i arr[1:] if i <= base_data]
upper_data=[i for i in arr[1:] if i >= base_data]
return quiksort(lower_data) + base_data +quiksort(upper_data)
广度优先搜索算法 #处理无向图
from collections import deque
def search (name,graph):#graph 定义的判断当前节点的周围节点的一个字典
search_que=deque()
search_que+=graph[name]
searched=[]
while search_que:
person=search_que.popleft()
if person not in search:
if is_true_person(person):
print("find")
return True
else:
search_que+=graph[perch]
search.append(person)
return False
狄克斯特拉算法#用于有向图的搜索`
infinity = float("inf")
costs = {}
costs["a"] = 6
costs["b"] = 2
costs["fin"] = infinity
graph["a"] = {}
graph["a"]["fin"] = 1
graph["b"] = {}
graph["b"]["a"] = 3
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
def dijsk(costs,graph,neighbors):
node=find_lowest_cost_node(costs)
while node is not None:
neighbors=graph[node]
cost=costs[node]
for n in neighbors.keys():
new_cost=cost+neighbors[n]
if new_cost<costs[n]:
costs[n]=new_cost
parents[n]=node
processed.append(node)
node=find_lowest_cost_node(costs)
判断问题是不是NP完全问题
元素较少时算法的运行速度非常快,但随着元素数量的增加,速度会变得非常慢。
涉及“所有组合”的问题通常是NP完全问题。
不能将问题分成小问题,必须考虑各种可能的情况。这可能是NP完全问题。
如果问题涉及序列(如旅行商问题中的城市序列)且难以解决,它可能就是NP完全问题。
如果问题涉及集合(如广播台集合)且难以解决,它可能就是NP完全问题。
如果问题可转换为集合覆盖问题或旅行商问题,那它肯定是NP完全问题。
二叉树的好处
在这种数组中查找时,最快的方式是二分查
找,但问题是每当有新数据时,都必须将数据插入该数组并重新排序,因为二分查找仅
在数组有序时才管用。如果能将数据插入到数组的正确位置就好了,这样就无需在插入后再排
序。为此,有人设计了一种名为二叉查找树(binary search tree)的数据结构。
布隆过滤器原理
如果想判断一个元素是不是在一个集合里,一般想到的是将集合中所有元素保存起来,然后通过比较确定。链表、树、散列表(又叫哈希表,Hash table)等等数据结构都是这种思路。但是随着集合中元素的增加,我们需要的存储空间越来越大。同时检索速度也越来越慢。
Bloom Filter 是一种空间效率很高的随机数据结构,Bloom filter 可以看做是对 bit-map 的扩展, 它的原理是:
当一个元素被加入集合时,通过 K 个 Hash 函数将这个元素映射成一个位阵列(Bit array)中的 K 个点,把它们置为 1。检索时,我们只要看看这些点是不是都是 1 就(大约)知道集合中有没有它了: