每天学一点之Python100例(25~26)

每天学一点,形成一种知识复利

问题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)


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值