donnemartin / donnemartin/interactive-coding-challenges

quicksort solution is incorrect (auxiliary space used)

Open
#268 0 comments 0 reactions 0 assignees View on GitHub
needs-review
Dominant language
Python
Stars
31.8k
Forks
4.7k
PR merge metrics
No merged PRs in 30d

Description

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:
```python
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]
```

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.