算法图解学习笔记_选择排序

数组与链表

访问方式:随机访问、顺序访问

数组支持随机访问,查找速度快,用的多
链表插入和删除方便

选择排序

时间复杂度: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-

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值