每天学一点之Python100例(23~24)

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

问题23:简单排序算法之插入排序
分析:什么是插入排序?插入排序基本操作方式是插入,不断把一个个元素插入一个序列,最终得到排序序列。其中最主要的思想是缓存当前需要排序的元素,记录当前元素的位置,当前需要排序的元素跟已经排序好的元素比较,比它大的向后移动,比它小的向前移动。
demoCode:
#! /usr/bin/python3

def insert_sort(lst_sort):
for i in range(1,len(lst_sort)):
x = lst_sort[i]
index = i
while index > 0 and lst_sort[index - 1] > x:
lst_sort[index] = lst_sort[index - 1]
index -= 1
lst_sort[index] = x
new_list = [3,43,23,57,24,5,38,243,35]
insert_sort(new_list)
print(new_list)

问题24:简单排序算法之选择排序
分析:选择排序的基本思想:1.维护需要考虑的所有记录中最小的i个记录的已排序序列
2.每次从剩余未排序的记录中选取关键码最小记录,将其放在已排序序列记录的后面,作为序列的第i+1个记录,使已排序序列增长;3.以空序列作为排序工作的开始,做到尚未排序的序列里只剩一个元素时,只需直接将其放在已排序的记录之后,整个排序就完成了
demoCode:
#! /usr/bin/python3

def select_sort(lst_sort):
for i in range(len(lst_sort) - 1):
index = i
for j in range(i, len(lst_sort)):
if lst_sort[j] < lst_sort[index]:
index = j
if i != index:
lst_sort[i], lst_sort[index] = lst_sort[index], lst_sort[i]

new_list = [3,43,23,57,24,5,38,342,35]
select_sort(new_list)
print(new_list)


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值