二分查找
- 二分查找的时间复杂度:O(logn),log都是以2为底
- 简单查找法:O(n),线性时间
- 算法的速度指的不是时间而是操作数的增长,即要进行多少步操作
"""算法图解——二分查找"""
def binary_search(alist, item):
low = 0
high = len(alist) - 1
while low <= high:
mid = (low + high)//2
guess = alist[mid]
if guess < item:
low = mid + 1
elif guess > item:
high = mid - 1
else:
return mid
return None
my_list = [1, 3, 5, 7, 9]
print(binary_search(my_list, 8))
print(binary_search(my_list, 7))
None
3
1. 小结
- 算法的运行时间并不以秒为单位
- 算法的运行时间是从增速角度度量的
- O(logn)的速度快于O(n)
选择排序
1. 内存工作原理
计算机就像很多抽屉的集合,每个抽屉都有自己的地址,需要将数据存储到内存时,请求计算机提供存储空间
2. 链表
- 优点:方便插入和删除数据元素,节省内存空间
- 缺点:访问元素不方便,必须从头开始
3. 数组
- 优点:方便访问数据
- 缺点:插入删除元素麻烦
4. 选择排序
"""找出列表中的最小元素"""
def findsmallest(alist):
smallest = alist[0]
smallest_index = 0
for i in range(len(alist)):
if alist[i] < smallest:
smallest = alist[i]
smallest_index = i
return smallest
"""选择排序"""
def selectionSort(alist):
new_list = []
for i in range(len(alist)):
smallest = findsmallest(alist)
new_list.append(smallest)
alist.remove(smallest)
return new_list
print(selectionSort([5, 3, 6, 2, 10]))
[2, 3, 5, 6, 10]
5. 小结
- 数组的读取速度很慢,且同一个数组的数据类型要一致
- 链表的插入删除方便