算法--排序python实现

本文深入讲解两种基础排序算法——选择排序和插入排序。选择排序通过不断寻找最小元素并将其置于正确位置来完成排序,而插入排序则在已排序序列中找到合适位置插入新元素。文章提供了详细的算法步骤和Python代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

记录一些基本排序算法,全当是复习巩固了。

 

1:选择排序

核心思想:每一次都从无序的序列中挑选中最小值,并把它放到相应的位置上。

假设有一堆数字卡片,卡片是无序排列的,现在需要按照卡片上数字从小到大排列。

 

算法步骤:

1. Find the smallest card. Swap it with the first card.
2. Find the second-smallest card. Swap it with the second card.
3. Find the third-smallest card. Swap it with the third card.
4. Repeat finding the next-smallest card, and swapping it into 
   the correct position until the array is sorted.
step1、找出数字最小的卡片,然后把它放到第一个位置

step2、找出数字第二小的卡片,然后把它放到第二个位置上

step3、找出数字第三小的卡片,然后把它放到第三个位置上

step4、重复上述过程直到满足要求

代码实现:

def selectionsort(lt):
    for i in range(len(lt)):
        temp = lt[i]
        tempid = i
        j = i+1
        
        while j < len(lt):
            if temp > lt[j]:
                tempid = j
                temp = lt[tempid]
            j = j+1

        lt[i], lt[tempid] = lt[tempid],lt[i]        
    print lt

lt = [2,6,12,9,20,4,67,23,89]    

selectionsort(lt)

算法时间复杂度 O\left ( n^{2} \right ),空间复杂度O\left ( c \right )

 

2、插入排序

在已经排好序的序列中,插入新的元素。

插入排序伪代码

 

代码:

def InsertionSort(l):
    for j in range(1,len(l)):
        key = l[j]
        i = j-1
        while i >= 0 and l[i] > key:
            l[i+1] = l[i]
            i = i-1
        l[i+1] = key
      
    return l


A = [31,41,59,26,41,58]            
b = InsertionSort(A.copy())  

算法时间复杂度 O\left ( n^{2} \right ),空间复杂度O\left ( c \right )

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

nobrody

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值