python实现各种排序

冒泡:

def bubble_sort(arry):
    #获得数组的长度
    n = len(arry)                   
    for i in range(n):
        for j in range(1,n-i):
            #如果前者比后者大
            if  arry[j-1] > arry[j] :  
                #则交换两者     
                arry[j-1],arry[j] = arry[j],arry[j-1]      
    return arry

选择:

def select_sort(ary):
    n = len(ary)
    for i in range(0,n):
        #最小元素下标标记
        min = i                             
        for j in range(i+1,n):
            if ary[j] < ary[min] :
                #找到最小值的下标
                min = j
        #交换两者                     
        ary[min],ary[i] = ary[i],ary[min]   
    return ary

插入:

def insert_sort(ary):
    n = len(ary)
    for i in range(1,n):
        if ary[i] < ary[i-1]:
            temp = ary[i]

            #待插入的下标
            index = i           
            #从i-1 循环到 0 (包括0)
            for j in range(i-1,-1,-1):  
                if ary[j] > temp :
                    ary[j+1] = ary[j]
                    #记录待插入下标
                    index = j   
                else :
                    break
            ary[index] = temp
    return ary

快排:

def quick_sort(ary):
    return qsort(ary,0,len(ary)-1)

def qsort(ary,left,right):
    #快排函数,ary为待排序数组,left为待排序的左边界,right为右边界
    if left >= right : return ary
    key = ary[left]     #取最左边的为基准数
    lp = left           #左指针
    rp = right          #右指针

    while lp < rp :
        while ary[rp] >= key and lp < rp :
            rp -= 1
        while ary[lp] <= key and lp < rp :
            lp += 1
        ary[lp],ary[rp] = ary[rp],ary[lp]
    ary[left],ary[lp] = ary[lp],ary[left]
    qsort(ary,left,lp-1)
    qsort(ary,rp+1,right)
    return ary

堆排序:

def heap_sort(ary) :
    n = len(ary)
    #最后一个非叶子节点
    first = int(n/2-1)       
    #构造大根堆
    for start in range(first,-1,-1) :     
        max_heapify(ary,start,n-1)

    #堆排,将大根堆转换成有序数组
    for end in range(n-1,0,-1):           
        ary[end],ary[0] = ary[0],ary[end]
        max_heapify(ary,0,end-1)
    return ary

#最大堆调整:将堆的末端子节点作调整,使得子节点永远小于父节点
#start为当前需要调整最大堆的位置,end为调整边界
def max_heapify(ary,start,end):
    root = start
    while True :
        #调整节点的子节点
        child = root*2 +1               
        if child > end : break
        if child+1 <= end and ary[child] < ary[child+1] :
            #取较大的子节点
            child = child+1
        #较大的子节点成为父节点             
        if ary[root] < ary[child] :    
            #交换 
            ary[root],ary[child] = ary[child],ary[root]     
            root = child
        else :
            break

你可能感兴趣的:(数据结构与算法)