问题25:快速排序
分析:快速排序基本过程:1.选择一种标准,把被排序序列中的记录按这种标准分为大小两组。显然,从整体的角度,这两组记录的顺序已定,较小一组的记录应该排在前面;2.采用同样方式,递归地分别划分得到的这两组记录,并继续递归地划分下去;3.划分总是得到越来越小的分组,直到每个记录组中最多包含一个记录时,整个序列的排序完成。
demoCode:
#! /usr/bin/python3
def quick_sort(lst, left, right):
if left >= right:return
left_index = left
right_index = right
pivot = lst[left_index]
while left_index < right_index:
while left_index < right_index and lst[right_index] >= pivot:
right_index -= 1
if left_index < right_index:
lst[left_index] = lst[right_index]
left_index += 1
while left_index < right_index and lst[left_index] <= pivot:
left_index += 1
if left_index < right_index:
lst[right_index] = lst[left_index]
right_index -= 1
lst[left_index] = pivot
quick_sort(lst, left, left_index - 1)
quick_sort(lst, left_index + 1, right)
new_list = [3,43,23,57,24,5,38,342,35]
quick_sort(new_list, 0, len(new_list) - 1)
print(new_list)
问题26:冒泡排序
分析:冒泡排序是一种典型通过交换元素消除逆序实现排序的方法,其中的基本操作是比较相邻记录,发现相邻的逆序对时就交换它们。通过反复比较和交换,最终完成整个序列的排序工作。
demoCode:
#! /usr/bin/python3
def bubble_sort(lst):
for i in range(len(lst)):
found = False
for j in range(1, len(lst) - i):
if lst[j - 1] > lst[j]:
lst[j - 1],lst[j] = lst[j],lst[j - 1]
found = True
if not found:
break
new_list = [3,43,23,57,24,5,38,342,35]
bubble_sort(new_list)
print(new_list)