常用 6 种排序算法(Python)

1. 冒泡排序
a = [10,9,8,7,6,5,4,3,2,1]
for i in range(len(a)-1):
    for j in range(len(a)-1-i):
        if( a[j] > a[j+1] ):
            temp = a[j]
            a[j] = a[j + 1]
            a[j + 1] = temp
print("排序后的列表为", a)
2. 选择排序
a = [10,9,8,7,6,5,4,3,2,1]
for i in range(len(a)-1):
    for j in range(i+1, len(a)):
        if( a[i] > a[j] ):
            temp = a[i]
            a[i] = a[j]
            a[j] = temp
print("排序后的列表为", a)
3. 选择法排序
a = [10,9,8,7,6,5,4,3,2,1]
for i in range(1, len(a)):
    wait = a[i]
    j = i - 1
    while j>=0:
        if( a[j] > wait ):
            a[j+1] = a[j]
        else:break;
        j = j - 1
    a[j+1] = wait
print("排序后的列表为", a) 
4. 折半法排序
a = [10,9,8,7,6,5,4,3,2,1]
for i in range(1, len(a)):
    wait = a[i]
    low = 0
    high = i - 1
    while( low <= high ):
        mid = (low + high) // 2
        if( wait < a[mid] ):
            high = mid - 1
        else:
            how = mid + 1
    j = i - 1
    while( j > high ):
        a[j +1] = a[j]
        j = j - 1
    a[high + 1] = wait

print("排序后的列表为", a) 
5. 希尔排序
a = [10,9,8,7,6,5,4,3,2,1]
step = len(a) // 2
while ( step > 0 ):
    for i in range(0+step, len(a), step):
        wait = a[i]
        j = i - 1
        while( j >= 0 ):
            if( a[j] > wait ):
                a[j + 1] = a[j]
            else:break
            j = j - 1
        a[ j + 1 ] = wait            
    step //= 2   
print("排序后的列表为", a) 
6. 桶排序
a = [10,9,8,7,6,5,4,3,2,1,20]
b = []
bucket = []
for i in range(max(a)+1):
    bucket.append(0)
for j in range(len(a)):
    bucket[a[j]] += 1
for k in range(max(a), 0,-1):
    for l in range(bucket[k], 0, -1):
        b.append(k)
print("排序后的列表为", b) 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值