Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
bones7456 opened this issue Dec 22, 2023 · 0 comments
Open

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

bones7456 opened this issue Dec 22, 2023 · 0 comments

Comments

@bones7456
Copy link

快速排序的精髓在于“减少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]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant