python算法

1.插入排序
def insert_sort(ls):
    for i in range(1,len(ls)):
        j = i
        while j >0 and ls[j-1] > ls[j]:
            tmp = ls[j]
            ls[j] = ls[j-1]
            ls[j-1] = tmp
            j -= 1


=================================================
2.冒泡排序
def bubble_sort(ls):
    n = len(ls)
    for j in range(1,n):
        for i in range(j,0-1):
            if ls[i-1] > ls[i]
                tmp = ls[i-1]
                ls[i-1] = ls[i]
                ls[i] = tmp


==================================================
3.快速排序
def quick_sort(ls):

    return ls if len(ls)<=1 else quick_sort([i for i in ls[1:] if i<=ls[0]]) +[ls[0]] + quick_sort([i for i in ls[1:] if i>ls[0]])

http://code.activestate.com/recipes/474088/     尾递归  @tail_call_optimized

==================================================
4.归并排序
def merge_sort(ls):
        if(len(ls) <= 1):  
            return ls
    left = merg_sort(ls[:len(ls)/2])
    right = merg_sort(ls[len(ls)/2:len(ls)])
    result = []
    while len(left) > 0 and len(right)> 0:
        if( left[0] > right[0]):
            result.append(right.pop(0))
        else:
            result.append(left.pop(0))
 
    if(len(left)>0): 
        result.extend(merg_sort(left))
    else: 
        result.extend(merg_sort(right))
    return result
==================================================
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值