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

quicksort solution is incorrect (auxiliary space used) #268

Open
wulymammoth opened this issue Oct 30, 2019 · 0 comments
Open

quicksort solution is incorrect (auxiliary space used) #268

wulymammoth opened this issue Oct 30, 2019 · 0 comments

Comments

@wulymammoth
Copy link

wulymammoth commented Oct 30, 2019

Awesome repo, but I came across the quicksort solution done here and I don't believe it's the canonical solution when quicksort is typically described to be an "in-place" sort. The implemented solution allocates new arrays in which values to the left and right are placed into their corresponding auxiliary arrays (lists) -- I've denoted the places that I see them in the code w/ a comment. I believe the implementation should utilize swaps w/o allocating auxiliary data structures. Lastly, the list concatenation also incurs a linear time cost as a new list/array is allocated and all elements in each sub-array must be copied over:

def _sort(self, data):
        if len(data) < 2:
            return data
        equal = [] # extra space
        left = [] # extra space
        right = [] # extra space
        pivot_index = len(data) // 2
        pivot_value = data[pivot_index]
        # Build the left and right partitions
        for item in data:
            if item == pivot_value:
                equal.append(item)
            elif item < pivot_value:
                left.append(item)
            else:
                right.append(item)
        # Recursively apply quick_sort
        left_ = self._sort(left)
        right_ = self._sort(right)
        return left_ + equal + right_ # O(n) [where n is the size of the original input]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants