Skip to content

Update the QuickSort Algorithm to minimise chance of O(n^2) #6095

Closed
@faiqali1

Description

@faiqali1

According to this question on StackOverflow it is better to use the median or a random value as a pivot.

Currently the implementation uses the last element as the pivot.

def quick_sort(collection: list) -> list:
    if len(collection) < 2:
        return collection
    pivot = collection.pop()  # <-- Use the last element as the first pivot
    greater: list[int] = []  
    lesser: list[int] = []  
    for element in collection:
        (greater if element > pivot else lesser).append(element)
    return quick_sort(lesser) + [pivot] + quick_sort(greater)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions