Skip to content

快速排序的实现方式有优化空间 #64

Open
@bones7456

Description

@bones7456

快速排序的精髓在于“减少swap的次数”,目前的实现代码中,swap次数偏多,不够精简,在GIF动图的演示里也能看出问题。
正确的实现方式可以参考wikipedia,以下是python实现方式的代码:

def quickSort(arr, left=None, right=None):
    left = 0 if not isinstance(left,(int, float)) else left
    right = len(arr)-1 if not isinstance(right,(int, float)) else right
    if left < right:
        partitionIndex = partition(arr, left, right)
        quickSort(arr, left, partitionIndex-1)
        quickSort(arr, partitionIndex+1, right)
    return arr

def partition(arr, left, right):
    pivot = arr[right]
    i, j= left, right - 1
    while True:
        while i<=j and arr[i]<pivot:
            i+=1
        while i<=j and arr[j]>=pivot:
            j-=1
        if i<j:
            swap(arr, i, j)
        else:
            break
    swap(arr, i, right)
    return i

def swap(arr, i, j):
    arr[i], arr[j] = arr[j], arr[i]

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions