排序汇总

和自甴很熟 提交于 2019-11-26 10:20:55

快排,归并,堆排汇总

#快排1
def quick_sort1(arr):
    if len(arr)<=1:
        return arr
    target=arr[0]
    return quick_sort1([i for i in arr[1:] if i<=target])+[target]+quick_sort1([i for i in arr[1:] if i>target])
print(quick_sort1([5,7,8,9,6,5,4]))
#######################################################
#快排2,原数组修改,无返回值
def quick_sort2(arr,start,end):
    if start<end:
        p1,p2=out_sort(arr,start,end)
        quick_sort2(arr,start,p1)
        quick_sort2(arr,p2,end)
        return 
def out_sort(arr,start,end):
    p1,p2=start-1,end+1
    cur,target=start,arr[start]
    while cur<p2:
        if arr[cur]<target:
            arr[cur],arr[p1+1]=arr[p1+1],arr[cur]
            p1+=1
            cur+=1
        elif arr[cur]==target:
            cur+=1
        else:
            arr[cur],arr[p2-1]=arr[p2-1],arr[cur]
            p2-=1
    return p1,p2
a=[5,7,8,9,6,5,4]
quick_sort2(a,0,6)
print(a)
########################################################
#归并,开辟空间覆盖原数组,无返回值
def gb_sort(arr,start,end):
    if start<end:
        mid=(start+end)>>1
        gb_sort(arr,start,mid)
        gb_sort(arr,mid+1,end)
        gb(arr,start,mid,end)

def gb(arr,s,m,e):
    p1,p2=s,m+1
    tmp=[]
    while p1<=m and p2<=e:
        if arr[p1]<arr[p2]:
            tmp.append(arr[p1])
            p1+=1
        else:
            tmp.append(arr[p2])
            p2+=1
    while p1<=m:
        tmp.append(arr[p1])
        p1+=1
    while p2<=e:
        tmp.append(arr[p2])
        p2+=1
    arr[s:e+1]=tmp[:]
    return
a=[5,7,8,9,6,5,4]
gb_sort(a,0,len(a)-1)
print(a)
#########################################################
#堆排
def build_heap(arr):
    lenth=len(arr)
    for i in range((lenth-2)>>1,-1,-1):
        adjust_heap(arr,i,len(arr))
    return 
def adjust_heap(arr,i,lenth):
    root=i
    son=root*2+1
    while son<lenth:
        if son+1<lenth and arr[son+1]>arr[son]:
            son+=1
        if arr[son]>arr[root]:
            arr[son],arr[root]=arr[root],arr[son]
            root=son
            son=root*2+1
        else:
            break
def heap_sort(arr):
    build_heap(arr)
    for end in range(len(arr)-1,-1,-1):
        arr[0],arr[end]=arr[end],arr[0]
        adjust_heap(arr,0,end)
    return arr
print(heap_sort([5,7,8,9,6,5,4]))
    

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!