jizanthapus
jizanthapus

Reputation: 159

quicksort in place performance (python)

I was asked to write an 'in place' Quicksort version. Created two internal functions - a recursive one and an 'in place sorting' one that chooses random pivot (Question required so), sorts the list in place and returns the pivot's index after sorting.

     import random

def quicksort(lst):

    def innerfunc(lst, start=0, end=(len(lst) - 1)):   
        temporal_pivot = subfunc(lst, start, end)

        if (end - start > 1): 
            if (temporal_pivot == start or temporal_pivot == start + 1):
                innerfunc(lst, temporal_pivot + 1, end)

            elif (temporal_pivot == end or temporal_pivot == end - 1):
                innerfunc(lst, 0 , temporal_pivot - 1)

            else:
                innerfunc(lst, 0 , temporal_pivot - 1), innerfunc(lst, temporal_pivot + 1, end)


    def subfunc(l, start, end):
        i_random = random.randint(start, end)  # chooses random index!
        l[i_random], l[start] = l[start], l[i_random]

        i_pivot = start
        pivot = l[start]

        i = end
        while i > i_pivot:
            if l[i] <= pivot:
                l.insert(i_pivot, l[i])
                i_pivot += 1
                l.pop(i + 1)

            else:
                i = i - 1

        return i_pivot


    return innerfunc(lst)

The problem is running time -

Lists that contain 100 elements or more are sorted very slowly.

Do you have an Idea how to improve "subfunc" algorithm and my Quicksort performance?

Thank you!

Oren

Upvotes: 0

Views: 318

Answers (2)

NPE
NPE

Reputation: 500317

The problem are the repeated calls to l.insert() and l.pop(). Each of these has O(n) complexity, whereas you want each iteration of the loop to be O(1).

You need to rework the function so it works by swapping elements instead of performing repeated insertions and removals.

You can find some pseudocode in Wikipedia.

Upvotes: 2

burnall
burnall

Reputation: 842

It seems that subfunc is not efficient - loop and insert into array part. I am not Python programmer but I suggest it can cause memory reallocation and cost O(n) operations

Upvotes: 0

Related Questions