def quick_sort(arr, low, high):
def partition(arr, low, high):
i = (low - 1) # 最小元素索引
pivot = arr[high]
for j in range(low, high):
# 当前元素小于或等于 pivot
if arr[j] <= pivot:
i = i + 1
arr[i], arr[j] = arr[j], arr[i]
arr[i + 1], arr[high] = arr[high], arr[i + 1]
return (i + 1)
if low < high:
pi = partition(arr, low, high)
quick_sort(arr, low, pi - 1)
quick_sort(arr, pi + 1, high)
arr = [10, 7, 8, 9, 1, 5]
n = len(arr)
quick_sort(arr,0,n-1)
print ("排序后的数组:")
for i in range(n):
print (arr[i],end=' ')
第一题
example = [1, 3, 4, 5, 2, 6, 9, 7, 8, 0]
a = 0
b = len(example) - 1
def division(number, head, tail):
base = number[head]
while (head < tail):
while (head < tail and number[tail] >= base):
tail -= 1
number[head] = number[tail]
while (head < tail and number[head] <= base):
head += 1
number[tail] = number[head]
number[head] = base
return head
def quickSort(number, head, tail):
if (head < tail):
base = division(number, head, tail)
# print(number[base],"\n")
quickSort(number, head, base - 1)
quickSort(number, base + 1, tail)
else:
print(number)
quickSort(example, a, b)
第二题
count = 0
def hanoi(n, a, b, c):
if n > 0:
hanoi(n - 1, a, c, b)
print('moving from [%s] to [%s]' % (a, c))
global count
count += 1
hanoi(n - 1, b, a, c)
n = int(input('n'))
hanoi(n, 'A', 'B', 'C')
print(f'一共移动了{count}次')