学习日志017--python的几种排序算法

冒泡排序

python 复制代码
def bubble_sort(alist):
    i = 0
    while i<len(alist):
        j=0
        while j<len(alist)-1:
            if alist[j]>alist[j+1]:
                alist[j],alist[j+1] = alist[j+1],alist[j]
            j+=1

        i+=1

l = [2,4,6,8,0,1,3,5,7,9]
bubble_sort(l)
print(l)

选择排序

python 复制代码
def select_sort(alist):
    i = 0
    while i<len(alist)-1:
        temp = i
        j=i+1
        while j<len(alist):
            if alist[temp]>alist[j]:
                temp = j
            j+=1
        if not temp == i:
            alist[i],alist[temp] = alist[temp],alist[i]
        i += 1
l = [6, 4, 5, 3, 8, 9, 2, 1, 7]
select_sort(l)
print(l)

直接排序

python 复制代码
def insert_sort(alist):
    i=1
    while i<len(alist):
        temp = alist[i]
        j = i
        while j>0 and alist[j - 1] > temp:
            alist[j] = alist[j-1]
            j-=1
        alist[j] = temp
        i+=1
l = [2,4,6,8,0,1,3,5,7,9]
insert_sort(l)
print(l)

快速排序

python 复制代码
def part(alist,l,r):
    p = alist[l]

    while l<r:
        while l<r and alist[r]>p:
            r-=1
        alist[l] = alist[r]

        while l<r and alist[l]<p:
            l+=1
        alist[r] = alist[l]
    alist[l] = p

    return l

def quick_sort(alist,l,r):
    if l<r:
        p_index = part(alist, l, r)
        print(alist)
        quick_sort(alist,l,p_index-1)
        quick_sort(alist,p_index+1,r)

l = [6, 4, 5, 3, 8, 9, 2, 1, 7]
n = len(l)-1
quick_sort(l,0,n)
print(l)

希尔排序

python 复制代码
def shell_sort(alist):
    n = len(alist)
    gap = n//2
    while gap>0:
        for i in range(gap,n):
            temp = alist[i]
            j = i
            while alist[j-gap] > temp and j >= gap:
                alist[j] = alist[j-gap]
                j -= gap
            alist[j] = temp

        gap = gap // 2
    return arr

arr = [6, 4, 5, 3, 8, 9, 2, 1, 7]
print("排序前:", arr)
sorted_arr = shell_sort(arr)
print("排序后:", sorted_arr)

xmind

相关推荐
2301_7735536213 小时前
Navicat模型工具高级应用:怎样自定义模型节点颜色样式_机制解析
jvm·数据库·python
2301_8166602113 小时前
mysql在生产环境执行DDL的风险_如何使用GH-OST在线修改
jvm·数据库·python
南子北游13 小时前
计算机视觉学习(二)图像分类
人工智能·学习·计算机视觉
m0_7436239213 小时前
mysql如何限制用户连接数_使用MAX_USER_CONNECTIONS优化并发
jvm·数据库·python
解救女汉子13 小时前
如何防止SQL注入式非法删除_使用预处理语句绑定参数
jvm·数据库·python
2301_7826591813 小时前
C#怎么将集合分块处理_C#如何使用Chunk方法【实战】
jvm·数据库·python
Full Stack Developme13 小时前
Hutool XML 操作教程
xml·windows·python
qq_4240985613 小时前
如何分析enq- TM - contention_外键未建索引导致的表级锁阻塞
jvm·数据库·python
淘矿人13 小时前
2026大模型API中转平台深度评测:weelinking领衔五大服务商横向实测与选型指南
开发语言·人工智能·python·oracle·数据挖掘·php·pygame
qq_3345635513 小时前
如何让水平滚动条始终固定在页面底部可见
jvm·数据库·python