# #选择排序(从小到大)
def selectionSort(arr):
for i in range(len(arr)):#选择多少次
min_idx = i#假设最小元素的索引为ifor j in range(i + 1, len(arr)):
if arr[min_idx]> arr[j]:
min_idx = j
arr[i], arr[min_idx]= arr[min_idx], arr[i]return arr
arr =[98, 23, 12, 43, 59]
print("排序后的数组:",selectionSort(arr))
排序后的数组:[12,23,43,59,98]
chaptet3 递归
##3.1递归#寻找盒子中的钥匙"""方法1:使用while循环"""
from numpy import empty
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 look_for_kry(box):
for item in box:
if item.is_a_box():
look_for_key(item)#递归elif item.is_a_key():
print("found the key")
#3.3.2 递归调用栈
def fact(x): #x!if x == 1:
return 1
else:
return x * fact(x-1)#递归调用
6
chapter 4快速排序
##4.1分而治之(divide and conquer,D&C)"""
分而治之是一种通用的算法
分而治之解决问题的过程包括两个步骤(工作原理):
step1.找出简单的基线条件
step2.确定如何缩小规模,使其符合基线条件
""""""
#Q:将一块地均匀分成方块且分出的方块要尽可能大
#A: step1.找出这块地可容纳的最大方块
step2.在剩余的地中找出可容纳的最大方块
step3.一直递归,直至将地分完
"""#使用循环将一个数字数组相加
def sum(arr):
total = 0
for x in arr:
total += x
return total
print(sum([2,4,6]))#使用递归函数完成数组相加"""
step1:找出简单的基线条件(数组不包含任何元素或只包含一个元素)
step2:缩小规模(计算数组列表中除第一个数字外的其他数字的总和,将其与第一个数字相加)
"""
def sum_rexursion(arr):
if arr ==[]:
return 0
return arr[0]+sum(arr[1:])
print(sum([2,4,6]))#%%
def sum(arr):
if arr ==[]:
return 0
a = arr[0]
del arr[0]#del删除的是变量,而不是数据return sum(arr)+a
print(sum([2,4,6]))
121212
##练习#4.2 编写一个递归函数来计算列表包含的元素数
def lenList(list):
if list ==[]: #基线条件:列表中的元素是否为空return 0
else:
return 1+lenList(list[1:])
print("列表包含的元素个数为:",lenList([2,4,6]))
列表包含的元素个数为:3
#4.3 找出列表中的最大数字
def find_max(list):
tmp = list.pop(0)if list ==[]:
return tmp
max = find_max(list)if max > tmp:
return max
else:
return tmp
print("找出列表中最大的元素:",find_max([2,4,6,7,9]))
找出列表中最大的元素:9
#4.4递归实现二分查找
def HalfSearch(OrdderedList, key, left, right):
if left > right:#二分查找算法要求数组按顺序排列return None
mid =(left + right)//2
if key == OrdderedList[mid]:
return mid
elif key > OrdderedList[mid]: #如果关键字大于猜测的数值return HalfSearch(OrdderedList, key, mid+1, right)
else: #如果关键字小于猜测的数值return HalfSearch(OrdderedList, key, left, mid-1)
a =[1,2,3,4,5,6,7,8,9]#print(len(a))
user_input = int(input("请输入你要查询的值:"))
left = 0
right = len(a)-1
index = HalfSearch(a, user_input, left, right)#调用递归二分查找算法
print(index)
请输入你要查询的值:32
#4.2 快速排序"""
快速排序算法也运用了分而治之的思想
快速排序算法的步骤:
step1.选择基准值
step2.将数组分成两个子数组:小于基准值的元素和大于基准值的元素
step3.对这两个子数组进行快速排序
"""
def quickSort(arr):
if len(arr)<2:
return arr #基线条件:空的或只包含一个元素的数组是“有序”的
else:
pivot = arr[0]#递归条件(pivot)为基准值less=[i for i in arr[1:]if i<= pivot]#由所有小于基准值的元素组成的子数组
greater =[i for i in arr[1:]if i> pivot]#由所有大于基准值的元素组成的子数组return quickSort(less) + [pivot] + quickSort(greater)
print("快速排序算法:",quickSort([10,5,2,3]))