希尔排序,归并排序,快速排序,三路排序(python实现)

希尔排序:

def shellSort(alist):
    gap=len(alist)//2
    while gap>0:
        for startPos in range(gap):
            gapInsertionSort(alist,startPos,gap)
        gap=gap//2
def gapInsertionSort(alist,startPos,gap):
    for i in range(startPos+gap,len(alist),gap):
        position=i
        currentValue=alist[i]
        while position-gap>=0 and alist[position-gap]>currentValue:
                alist[position]=alist[position-gap]
                position=position-gap
        alist[position]=currentValue

归并排序:

def mergeSort(alist):
    if len(alist)>1:
        if len(alist)<=16:
            alist=shellSort(alist) #一个优化,在数组个数比较小时,插入排序比归并排序更快
            return alist
        mid=len(alist)//2
        lefthalf=alist[:mid]
        righthalf=alist[mid:]
        lefthalf=mergeSort(lefthalf)
        righthalf=mergeSort(righthalf)
        if lefthalf[-1]<=righthalf[0]:
            alist=lefthalf+righthalf
            return alist
        i,j,k=0,0,0
        while i

快速排序:

from random import randint
def quickSort(alist):
    quickSortHelper(alist,0,len(alist)-1)
    return alist
def quickSortHelper(alist,first,last):
    if firstcurrentvalue and position>first:
            alist[position]=alist[position-1]
            position=position-1
        alist[position]=currentvalue
    return alist
def partition(alist,first,last):
    rand=randint(first,last) #随机取标定点,解决近乎有序的列表
    alist[first],alist[rand]=alist[rand],alist[first]
    pivotvalue=alist[first]
    leftmark=first+1
    rightmark=last
    dont=False
    while not done:
        while leftmark<=rightmark and alist[leftmark]=leftmark and alist[rightmark]>pivotvalue:
            rightmark-=1
        if leftmark>rightmark:
            done=True
        else:
            alist[leftmark],alist[rightmakr]=alist[rightmark],alist[leftmark]
            leftmark+=1
            rightmark-=1
    alist[first],alist[rightmark]=alist[rightmark],alist[first]
    return rightmark

三路排序:

def quickSort3Ways(alist):
    quickSortWaysHelper(alist,0,len(alist)-1)
    return alist
def quickSortWaysHelper(alist,first,last):
    if first=gt:
            done=True
    alist[first],alist[lt]=alist[lt],alist[first]
    lt-=1 #lt -1表示的是小于pivoluvalue最大索引
    return lt,gt

 

你可能感兴趣的:(希尔排序,归并排序,快速排序,三路排序(python实现))