1.汉诺塔
def hanoi(n, a, b, c):
if n > 0:
hanoi(n-1, a, c ,b)
print('moving from {} to {}'.format(a, c))
hanoi(n-1, b, a, c)
2.列表查找
def line_search(li, val):
for index, x in enumerate(li):
if x == val:
#print(index)
return index
else:
return None
3.二分查找
def bina_search(li, val):
left = 0
right = len(li) - 1
while left <= right:
mid = (left + right) // 2
if li(mid) == val:
return mid
elif li(mid) > val:
right = mid - 1
else:
left = mid + 1
else:
return None
4.冒泡排序
def bubble_sort(li):
for i in range(len(li)-1):
flag = False
for j in range(len(li)-1-i):
if li[j] > li[j+1]:
li[j], li[j+1] = li[j+1], li[j]
flag = True
if not flag:
return
5.1选择排序
def select_sort(li):
li_new = []
for i in range(len(li)):
min_val = min(li)
li_new.append(min_val)
li.remove(min_val)
return li_new
5.2选择排序
def select_sort(li):
for i in range(len(li)-1):
min_loc = i
for j in range(i+1, len(li)):
if li(j) < li(min_loc):
min_loc = j
li[i], li[min_loc] = li[min_loc], li[i]
6.插入排序
def insert_sort(li):
for i in range(1, len(li)):
j = i - 1
temp = li[i]
while j >= 0 and li[j] > temp:
li[j+1] = li[j]
j -= 1
li[j+1] = temp
7.快速排序
def partition(li, left, right):
temp = li[left]
while left < right:
while left < right and li[right] >= temp:
right -= 1
li[left] = li[right]
while left < right and li[left] <= temp:
left += 1
li[right] = li[left]
li[left] = temp
return left
def quick_sort(li, left, right):
if left < right:
mid = partition(li, left, right)
quick_sort(li, left, mid-1)
quick_sort(li, mid+1, right)
快速排序
def quick_sort(data):
"""quick_sort"""
if len(data) >= 2:
mid = data[len(data)//2]
left, right = [], []
data.remove(mid)
for num in data:
if num >= mid:
right.append(num)
else:
left.append(num)
return quick_sort(left) + [mid] + quick_sort(right)
else:
return data
8.堆排序
def heap_sort(elems):
def siftdown(elems, e, begin, end): # 向下筛选
i, j = begin, begin * 2 + 1 # j为i的左子结点
while j < end:
if j + 1 < end and elems[j] > elems[j + 1]: # 如果左子结点大于右子结点
j += 1 # 则将j指向右子结点
if e < elems[j]: # j已经指向两个子结点中较小的位置,
break # 如果插入元素e小于j位置的值,则为3者中最小的
elems[i] = elems[j] # 能执行到这一步的话,说明j位置元素是三者中最小的,则将其上移到父结点位置
i, j = j, j * 2 + 1 # 更新i为被上移为父结点的原来的j的位置,更新j为更新后i位置的左子结点
elems[i] = e # 如果e已经是某个子树3者中最小的元素,则将其赋给这个子树的父结点
# 或者位置i已经更新到叶结点位置,则将e赋给这个叶结点。
end = len(elems)
for i in range(end // 2 - 1, -1, -1): # 构造堆序。
siftdown(elems, elems[i], i, end)
for i in range((end - 1), 0, -1): # 进行堆排序.i最后一个值为1,不需要到0
# print(elems)
e = elems[i] # 将末尾元素赋给e
elems[i] = elems[0] # 交换堆顶与最后一个元素
siftdown(elems, e, 0, i)
return (elems)