Python icon indicating copy to clipboard operation
Python copied to clipboard

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

Open faiqali1 opened this issue 2 years ago • 3 comments

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)

faiqali1 avatar Apr 12 '22 11:04 faiqali1

I can fix this

lt77777 avatar Apr 28 '22 20:04 lt77777

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

stale[bot] avatar Jul 10 '22 15:07 stale[bot]

Hi @faiqali1, I would like to contribute in this issue. Is it still open? Please guide me through this.

mahi072 avatar Sep 09 '22 15:09 mahi072

I would like to work on this issue.

Ashutosh2613 avatar Sep 14 '22 08:09 Ashutosh2613

Hi @mahi072 And @Ashutosh2613,

Yeah, the issue is still open. Apologies for the late reply.

The current issue, as stated in the title is that, it is better to choose the pivot at a random point then choosing the last element every time.

So using the Random module, choose a Random point between 0 & the length of the array and use that as a pivot.

faiqali1 avatar Sep 17 '22 15:09 faiqali1

HI @faiqali1! I'm new to contribution process. I can't find how fork this question, but here is the code:

import random

def quick_sort(collection: list) -> list:
    if len(collection) < 2:
        return collection
    pivot = random.choice(collection)  
    greater: list[int] = []
    lesser: list[int] = []
    for element in collection:
        (greater if element > pivot else lesser).append(element)
    return quick_sort(lesser) + quick_sort(greater)

Kate-Way avatar Sep 18 '22 00:09 Kate-Way

@faiqali1 Changes are made, please do review the changes!

Ashutosh2613 avatar Sep 28 '22 07:09 Ashutosh2613

@faiqali1 heyyy shall i work on this?

ruchikayadav1408 avatar Oct 01 '22 14:10 ruchikayadav1408