数组与链表
访问方式:随机访问、顺序访问
数组支持随机访问,查找速度快,用的多
链表插入和删除方便
选择排序
时间复杂度:O(n1/2n)=O(n*n)=O(n^2)
快速排序时间复杂度:O(n log n)
示例代码
ddef 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
递归
学习如何将问题分解成基线条件和递归条件
示例代码
从盒子里寻找钥匙
两种方法,递归只是让解决方案更清晰,并没有性能上的优势
- 使用循环
def look_for_key(main_box):
"""使用循环"""
pile = main_box.make_a_pile_to_look_through()
while pile is not empty:
box = pile.grab_a_box()
for item in box:
if item.is_a_box():
pile.append(item)
elif item.is_a_key():
print("found the key")
- 使用递归
def recursion_look_for_key(box):
"""使用递归"""
for item in box:
if item.is_a_box():
look_for_key(item)
elif item.is_a_key():
print("found the key")
基线条件和递归条件
由于递归函数调用自己,因此编写这样的函数很容易出错,进而导致无限循环。
基线条件指的是函数不再调用自己,从而避免无限循环。
示例
def countdown(i):
print(i)
# 基线条件
if i <= 0:
# 让程序结束
return
else:
countdown(i-1)
栈
先进后出
调用栈
压入(插入)、弹出(删除并读取)
调用另一个函数时,当前函数暂停并处于未完成状态
存储多个函数的变量,称为调用栈
递归调用栈
示例代码
def fact(x);
"""计算n!"""
if x == 1:
return 1
else:
return x*fact(x-1)
降低内存要求
- 重写代码,使用循环
- 使用尾递归
–END-