We are going to implement quicksort in Python.
The quicksort algorithm works by selecting a 'pivot' element and partitioning the array so that:
All elements less than the pivot come before it.
All elements greater than the pivot come after it.
Then we recursively apply the same process to the sub-arrays.
There are different ways to choose the pivot (first element, last element, random, median-of-three, etc.).
We'll choose the last element as the pivot for simplicity.
Steps for partition (Lomuto partition scheme):
We'll use the last element as the pivot.
We traverse the array with an index i that tracks the position of the last element in the "less than pivot" part.
For each element from low to high-1:
if the current element is less than or equal to the pivot, we increment i and swap the current element with the element at index i.
Finally, we swap the pivot (at high) with the element at i+1 (so the pivot is in its correct position).
Return the index of the pivot.
Alternatively, we can use Hoare's partition scheme. But let's stick to Lomuto for clarity.
However, note that the Lomuto partition scheme is less efficient when there are many duplicate elements.
We can also use a three-way partition (Dutch National Flag) for that, but let's do the standard one.
Let's write the quicksort function that sorts in-place.
We'll have:
quicksort(arr, low, high)
partition(arr, low, high) -> returns the pivot index
But note: we want to sort the entire array, so we can have a wrapper.
Alternatively, we can write a non-in-place version that returns a new sorted list, but the classic quicksort is in-place.
Let's do in-place.
However, note that the problem says "Implement the quicksort algorithm", so we can choose either.
But typically, quicksort is done in-place for efficiency.
Let's do:
def quicksort(arr, low, high):
if low < high:
pi = partition(arr, low, high)
quicksort(arr, low, pi-1)
quicksort(arr, pi+1, high)
def partition(arr, low, high):
pivot = arr[high]
i = low - 1
for j in range(low, high):
if arr[j] <= pivot:
i += 1
arr[i], arr[j] = arr[j], arr[i]
arr[i+1], arr[high] = arr[high], arr[i+1]
return i+1
But note: this is Lomuto. We can also do Hoare's which is more efficient in some cases, but let's keep it simple.
However, note that the above partition uses the last element as pivot. This can lead to worst-case O(n^2) on already sorted arrays.
We can improve by choosing a random pivot. But the problem doesn't specify.
Let's stick to the above for now.
Alternatively, we can write a helper function that sorts the entire array without requiring low and high.
But the problem says "in a language of your choice", so we can choose Python and do the above.
However, let's write a version that is non-recursive for the partition? No, we are doing recursive.
Let's code accordingly.
But note: the above in-place version modifies the original array.
If we want to return a new sorted array, we can do:
def quicksort(arr):
if len(arr) <= 1:
return arr
pivot = arr[-1]
left = [x for x in arr[:-1] if x <= pivot]
right = [x for x in arr[:-1] if x > pivot]
return quicksort(left) + [pivot] + quicksort(right)
But this is not in-place and uses extra memory.
Since the problem doesn't specify, I'll do the in-place version because it's the classic one.
However, let's note that the non-in-place version is easier to read and write, but less efficient in space.
But the problem says "implement the quicksort algorithm", so either is acceptable.
I'll do both? No, the problem says "in a language of your choice", so one implementation.
Let me choose the in-place version with Lomuto partition and random pivot to avoid worst-case on sorted arrays.
Steps for random pivot:
In partition, we choose a random index between low and high, swap it with the last element, and then proceed as before.
Let's adjust:
def partition(arr, low, high):
# Random pivot selection
pivot_index = random.randint(low, high)
arr[pivot_index], arr[high] = arr[high], arr[pivot_index]
pivot = arr[high]
i = low - 1
for j in range(low, high):
if arr[j] <= pivot:
i += 1
arr[i], arr[j] = arr[j], arr[i]
arr[i+1], arr[high] = arr[high], arr[i+1]
return i+1
But note: we are swapping the random pivot to the last position and then using the last element as pivot.
Alternatively, we can write a version without random and just use the last element, but let's do random to be safe.
However, the problem doesn't specify, so I'll do without random to keep it simple, but note the worst-case.
But the problem says "implement the quicksort algorithm", so it's acceptable to have the simple version.
Let me do the simple version without random, but then we must be cautious.
Alternatively, we can use the median-of-three method, but that's more complex.
Since the problem is about implementing quicksort, I think the simple version is acceptable.
But let's do the random version because it's a small change and avoids the worst-case in practice.
However, the random version requires the random module.
Let's do:
import random
and then in partition, choose a random pivot and swap to the end.
But note: the problem doesn't say we can use random, but it's standard in quicksort to avoid worst-case.
I think it's acceptable.
Alternatively, we can let the user choose the pivot? No.
Let's do the random pivot.
Code:
import random
def quicksort(arr):
if len(arr) <= 1:
return arr
# We are going to do in-place, so we need a helper that takes low and high.
_quicksort(arr, 0, len(arr)-1)
def _quicksort(arr, low, high):
if low < high:
pi = partition(arr, low, high)
_quicksort(arr, low, pi-1)
_quicksort(arr, pi+1, high)
def partition(arr, low, high):
# Random pivot selection
pivot_index = random.randint(low, high)
arr[pivot_index], arr[high] = arr[high], arr[pivot_index]
pivot = arr[high]
i = low - 1
for j in range(low, high):
if arr[j] <= pivot:
i += 1
arr[i], arr[j] = arr[j], arr[i]
arr[i+1], arr[high] = arr[high], arr[i+1]
return i+1
But note: the above partition is Lomuto. There's also Hoare's partition which is more efficient in terms of swaps.
However, let's stick to Lomuto for clarity.
But note: the above code will sort the array in-place and return nothing (the original array is sorted).
Let's test with a small example.
However, the problem doesn't require testing, just implementation.
I'll write the code as described.
But note: the random module must be imported.
Alternatively, we can avoid random by using the middle element? But then we have to adjust the partition.
Since the problem doesn't specify, I'll do the random pivot.
However, if we are not allowed to use random, we can use the last element without random.
Since the problem says "in a language of your choice", and we are using Python, we can use random.
But let's make it clear: we are using random to choose the pivot.
However, if the array is large and we are concerned about the worst-case, we use random.
But the problem doesn't specify the constraints.
I think it's acceptable.
Alternatively, we can write two versions? No, the problem asks for one implementation.
I'll write the in-place version with random pivot.
But note: the above code uses recursion and may hit recursion limit for large arrays.
We can do iterative quicksort using a stack, but the problem says "implement the quicksort algorithm", and recursive is standard.
Let's do recursive.
Code:
import random
def quicksort(arr):
"""
Sorts the array in-place using quicksort with random pivot.
"""
_quicksort(arr, 0, len(arr)-1)
def _quicksort(arr, low, high):
if low < high:
pi = partition(arr, low, high)
_quicksort(arr, low, pi-1)
_quicksort(arr, pi+1, high)
def partition(arr, low, high):
# Randomly choose a pivot index and swap with the last element
pivot_index = random.randint(low, high)
arr[pivot_index], arr[high] = arr[high], arr[pivot_index]
pivot = arr[high]
i = low - 1
for j in range(low, high):
if arr[j] <= pivot:
i += 1
arr[i], arr[j] = arr[j], arr[i]
arr[i+1], arr[high] = arr[high], arr[i+1]
return i+1
However, note that the above partition uses <= which means it puts equal elements on the left. This is fine.
But if we want to avoid worst-case with many duplicates, we might want three-way partition. But the problem doesn't specify.
Let's stick to this.
But note: the above code will work for any comparable elements (numbers, strings, etc.) as long as they support <=.
However, if we have custom objects, we need to define comparison. But that's beyond the scope.
We assume the array elements are comparable.
Let me write the code accordingly.
But the problem says "in a language of your choice", so I'll write in Python.
However, if we are to sort in descending order, we would change the comparison. But the problem doesn't specify.
We are doing ascending.
Let's output the code.
But note: the function quicksort doesn't return anything, it sorts in-place.
If we want to return the array for chaining, we can return arr at the end of quicksort, but that's not necessary.
Since the classic in-place quicksort doesn't return, I'll leave it without return.
However, in Python, it's common to return the array even when in-place for chaining? Not necessarily.
Let me check: list.sort() returns None, but sorted() returns a new list.
We are doing in-place, so we can follow list.sort() and return None.
But the problem says "implement the quicksort algorithm", so we can choose.
I'll return the array for convenience.
Actually, let's return the array so that we can do:
sorted_arr = quicksort(arr)
and then use sorted_arr? But note that it sorts in-place and then returns the same array.
So it's a bit confusing. Let's not return and just sort in-place.
But the problem doesn't specify the interface.
Since the problem says "implement the quicksort algorithm", I think it's acceptable to have an in-place sort that returns nothing.
However, in the non-in-place version we return a new array.
I think I'll do the in-place without return.
But let me see the problem statement: "Implement the quicksort algorithm in a language of your choice"
So I think the function should sort the array.
I'll write:
def quicksort(arr):
"""Sorts the array in-place using quicksort algorithm."""
_quicksort(arr, 0, len(arr)-1)
and then the helper.
But to be safe, let's return the array? Actually, the user might expect the function to return the sorted array.
Since we are doing in-place, we don't need to return, but it's common in Python to return the array when the function is named like a sorting function that returns a new array? No, sorted returns new, list.sort returns None.
We are doing in-place, so we are like list.sort. So return None.
However, if the array is empty, we don't want to call _quicksort with high=-1? Actually, len(arr)-1 for empty array is -1, and then low=0, high=-1, so low>high, so it doesn't do anything. That's safe.
Let's code accordingly.
But note: the random pivot selection: if low==high, then random.randint(low, high) returns low, which is the same as high, and then we swap with itself. That's okay.
However, in the partition function, if low==high, then the for loop runs from low to high-1, which is from low to low-1, so empty. Then we swap i+1 (which is low) with high (which is low). So it returns low. Then in _quicksort, we call with (low, pi-1) and (pi+1, high) which are both invalid because pi==low and then pi-1 < low, and pi+1 > high. So it stops. That's correct.
So the code is safe.
Let me write the complete code.
However, note: the random module must be imported.
I'll write:
import random
def quicksort(arr):
"""Sorts the array in-place using quicksort with random pivot."""
_quicksort(arr, 0, len(arr)-1)
def _quicksort(arr, low, high):
if low < high:
pi = partition(arr, low, high)
_quicksort(arr, low, pi-1)
_quicksort(arr, pi+1, high)
def partition(arr, low, high):
pivot_index = random.randint(low, high)
arr[pivot_index], arr[high] = arr[high], arr[pivot_index]
pivot = arr[high]
i = low - 1
for j in range(low, high):
if arr[j] <= pivot:
i += 1
arr[i], arr[j] = arr[j], arr[i]
arr[i+1], arr[high] = arr[high], arr[i+1]
return i+1
But note: the above code uses the random module. If we are not allowed to use random, we can change the pivot selection to, say, the middle element? But then we have to adjust the partition to not assume pivot is at the end.
Alternatively, we can do without random and just use the last element.
Since the problem doesn't specify, I'll do without random to avoid the import and keep it simple.
But then the worst-case is O(n^2) on sorted arrays.
However, for the purpose of this problem, it's acceptable.
Let me change to without random:
def partition(arr, low, high):
pivot = arr[high]
i = low - 1
for j in range(low, high):
if arr[j] <= pivot:
i += 1
arr[i], arr[j] = arr[j], arr[i]
arr[i+1], arr[high] = arr[high], arr[i+1]
return i+1
And remove the random import.
But note: the problem says "implement the quicksort algorithm", so the basic version is acceptable.
However, the random version is more robust.
Since the problem doesn't specify, I'll do the simple version without random.
But let me think: if the array is already sorted, then the pivot is the largest element, and we partition into one subarray of size n-1 and one of size 0, leading to O(n^2). That's bad.
But the problem doesn't specify the input.
I think it's better to do random to avoid that.
But the problem doesn't require handling worst-case.
Since the problem is about implementing the algorithm, I think the simple version is acceptable.
However, I remember that in many educational contexts, they use the last element as pivot.
I'll do the simple version without random.
But then I have to note that it's not optimized for sorted arrays.
Alternatively, we can use the first element? Same issue.
I'll do the last element.
Let me write the code without random.
However, the problem says "in a language of your choice", so I can choose Python and do the simple version.
But to be safe, I'll do the random version because it's a small change and avoids the worst-case.
But then I have to import random.
Since the problem doesn't specify the environment, I think it's acceptable.
But let me see: the problem says "implement the quicksort algorithm", and quicksort is often presented with random pivot to avoid worst-case.
I'll do the random version.
However, if the user doesn't want to use random, they can change it.
But the problem doesn't require that.
I'll do the random version.
But note: the random module might not be available in all Python environments? It's standard.
I think it's acceptable.
Alternatively, we can use time or hash to generate a random number? But that's overkill.
But then if the user writes sorted_arr = quicksort(arr), they get None.
So it's better to return the array? I think it's a matter of style.
Since the problem doesn't specify, I'll return the array.
Let me return the array.
Final code:
import random
def quicksort(arr):
"""Sorts the array in-place using quicksort with random pivot and returns the sorted array."""
_quicksort(arr, 0, len(arr)-1)
return arr
def _quicksort(arr, low, high):
if low < high:
pi = partition(arr, low, high)
_quicksort(arr, low, pi-1)
_quicksort(arr, pi+1, high)
def partition(arr, low, high):
pivot_idx = random.randint(low, high)
arr[pivot_idx], arr[high] = arr[high], arr[pivot_idx]
pivot = arr[high]
i = low - 1
for j in range(low, high):
if arr[j] <= pivot:
i += 1
arr[i], arr[j] = arr[j], arr[i]
arr[i+1], arr[high] = arr[high], arr[i+1]
return i+1
But note: the function _quicksort and partition are helper functions and not part of the public API.
We can also put them inside quicksort? But then recursion would be tricky because we need to call the helper.
Alternatively, we can define them inside and then use a closure? But that's overkill.
I'll leave them as separate functions.
However, to avoid exposing them, we can prefix with underscore.
That's what I did.
Now, let's consider edge cases:
Empty array: len(arr)=0, then low=0, high=-1, so _quicksort doesn't do anything. Then return arr (empty). That's fine.
Single element: low=0, high=0, so _quicksort doesn't do anything. Then return arr. That's fine.
So it's safe.
But note: the random pivot selection: if the array has one element, then low=high, and random.randint(low, high) returns low, and then we swap with itself. Then the for loop doesn't run because low==high, so j from low to high-1 is empty. Then we swap i+1 (which is low) with high (which is low). Then return low. Then in _quicksort, we call with (low, pi-1) which is (0, -1) and (pi+1, high) which is (1,0). Both are invalid. So it stops.
So it's safe.
Let's write the code accordingly.
However, the problem says "in a language of your choice", so I'll write in Python.
But note: the above code uses recursion and may cause recursion depth exceeded for large arrays.
We can change to iterative using a stack, but the problem doesn't specify.
Since the problem is about implementing the algorithm, and recursive is the standard way, I think it's acceptable.
But if the array is very large, we might get recursion limit error.
We can increase the recursion limit, or use iterative.
However, the problem doesn't specify the input size.
I think it's acceptable.
Alternatively, we can do tail recursion optimization? But Python doesn't do tail recursion optimization.
So for very large arrays, we should use iterative.
But the problem doesn't specify.
I'll stick to recursive.
If we want to avoid recursion, we can do:
def quicksort(arr):
stack = [(0, len(arr)-1)]
while stack:
low, high = stack.pop()
if low < high:
pi = partition(arr, low, high)
# push the larger subarray first to reduce stack depth?
# Actually, we can push in any order, but to limit stack depth, we push the larger one last.
# But let's not worry about that.
stack.append((low, pi-1))
stack.append((pi+1, high))
But then we need the partition function.
And we are still using random pivot.
But the problem doesn't specify recursive or iterative.
I think recursive is simpler and more common in textbooks.
So I'll do recursive.
However, the iterative version avoids recursion limit.
Since the problem doesn't specify, I'll do recursive.
But note: the problem says "implement the quicksort algorithm", and the algorithm is usually recursive.
So I think it's fine.
Let me write the recursive version.
But to be safe for large arrays, we can use iterative.
However, the problem doesn't specify the array size.
I'll do recursive and note that for large arrays we might need to increase recursion limit.
Alternatively, we can do:
code
if (high - low) < some_threshold:
use insertion sort for small arrays? That's an optimization.
But the problem doesn't ask for optimizations.
So I'll do the basic recursive version.
Final code:
import random
def quicksort(arr):
"""Sorts the array in-place using quicksort with random pivot and returns the sorted array."""
_quicksort(arr, 0, len(arr)-1)
return arr
def _quicksort(arr, low, high):
if low < high:
pi = partition(arr, low, high)
_quicksort(arr, low, pi-1)
_quicksort(arr, pi+1, high)
def partition(arr, low, high):
pivot_idx = random.randint(low, high)
arr[pivot_idx], arr[high] = arr[high], arr[pivot_idx]
pivot = arr[high]
i = low - 1
for j in range(low, high):
if arr[j] <= pivot:
i += 1
arr[i], arr[j] = arr[j], arr[i]
arr[i+1], arr[high] = arr[high], arr[i+1]
return i+1
However, note: the above code uses random.randint which is inclusive.
Let me test with a small example:
code
arr = [3, 2, 1]
quicksort(arr)
Let's simulate:
low=0, high=2.
Random pivot: say we pick index 1 (value 2). Then swap with index2: arr becomes [3,1,2]
pivot = 2.
i = -1.
j=0: arr[0]=3 <=2? No.
j=1: arr[1]=1 <=2? Yes -> i=0, swap arr[0] and arr[1] -> [1,3,2]
Then swap arr[i+1] (arr[1]) with arr[high] (arr[2]) -> [1,2,3]. Return 1.
Then we sort [0,0] and [2,2] which are single elements.
So it works.
But note: if we pick the last element (index2) as pivot, then we don't swap in the pivot selection, and then the same process.
So it's correct.
However, note that the partition function returns the index of the pivot after placing it.
And then we sort the two parts.
This is the standard Lomuto partition.
I think it's correct.
But note: the condition if arr[j] <= pivot means that we put elements equal to the pivot on the left. This is acceptable.
If we want to put equal elements on the right, we change to <, but then the pivot might not be in the correct position if there are duplicates? Actually, it will be, because we are using <= and then the pivot is placed at i+1, and all elements before i+1 are <= pivot, and after are > pivot? Not exactly, because we are using <= so the pivot (which is equal to itself) will be swapped to the left? Wait, the pivot is at the end, and we are comparing with <=, so when we see an element equal to the pivot, we swap it to the left. Then at the end, we swap the pivot (which is at the end) with the first element that is greater than the pivot? Actually, the pivot is at the end and we are swapping it with the element at i+1, which is the first element that is greater than the pivot? Let's see:
code
We have i that points to the last element that is <= pivot.
Then we swap the pivot (at high) with the element at i+1, which is the first element that is > pivot? Not necessarily, because we have been swapping elements that are <= pivot to the left, so the element at i+1 is the first element that is > pivot? Actually, after the loop, the elements from low to i are <= pivot, and from i+1 to high-1 are > pivot? Because we only swap when we see an element <= pivot, so the elements that are > pivot are left in place and we skip them. So at the end, the elements from low to i are <= pivot, and from i+1 to high-1 are > pivot. Then we swap the pivot (at high) with the element at i+1, so now the pivot is at i+1, and the element that was at i+1 (which is > pivot) is at the end. So the pivot is in its correct position, and the left part (low to i) are <= pivot, and the right part (i+2 to high) are > pivot? Wait, after swapping, the element at i+1 is the pivot, and the element at high is the one that was at i+1 (which is > pivot). So now the array is:
[elements <= pivot] (from low to i) then [pivot] at i+1, then [elements > pivot] (from i+2 to high) and then the element that was at i+1 (which is > pivot) is at high? Wait, we swapped arr[i+1] and arr[high]. So the element at high (the pivot) goes to i+1, and the element at i+1 goes to high.
So after the swap, the array from low to i: <= pivot
then at i+1: pivot
then from i+2 to high: the elements that were > pivot? But note that the element that was at i+1 (which was > pivot) is now at high, so the segment from i+2 to high-1 are the elements that were > pivot and were not moved, and then at high we have an element that is > pivot? Actually, the element at high is now the one that was at i+1, which is > pivot. So the segment from i+2 to high are all > pivot? But note that we didn't move the elements that are > pivot during the loop, so they are in the same order? And then we moved the pivot to i+1, and the element that was at i+1 (which is > pivot) to the end. So now the array is:
[low ... i] : <= pivot
[i+1] : pivot
[i+2 ... high] : > pivot? But note that the element at high is now the one that was at i+1, which is > pivot, and the rest from i+2 to high-1 are the ones that were > pivot and were not moved. So yes, the entire segment from i+1 to high is: at i+1 the pivot, and then from i+2 to high are > pivot? But wait, the pivot is at i+1, and then from i+2 to high-1 are the elements that were > pivot and were in the original array from i+1 to high-1? And then at high we have the element that was at i+1 (which is > pivot). So the segment from i+2 to high are all > pivot? Actually, the element at i+1 is pivot, so we don't care about it. The left part is [low, i] and the right part is [i+2, high]? But note that the pivot is in its final position.
So the partition is correct.
Therefore, the code is correct.
Let me write the code accordingly.
However, note that the random pivot selection might cause the same element to be chosen multiple times? That's okay.
We are using random.randint which is uniform.
So the expected running time is O(n log n).
But worst-case is still O(n^2) because random doesn't guarantee avoiding the worst-case? Actually, with random pivot, the worst-case is very unlikely, but possible. The expected running time is O(n log n).
So it's acceptable.
I'll write the code as above.
But note: the function quicksort returns the array. If we don't want to return, we can remove the return.
Since the problem doesn't specify, I'll return the array.
However, the problem says "implement the quicksort algorithm", and the algorithm is about sorting the array.
So I think returning the array is acceptable.
But in the interest of being consistent with in-place sorts in Python (like list.sort), we don't return.
But then the user must know that the array is sorted in-place.
Since the problem doesn't specify, I think it's better to return the array for convenience.
However, I'll follow the Python convention: list.sort() returns None.
So I'll return None.
But then the function name quicksort might be expected to return the sorted array? It's ambiguous.
I'll do:
code
def quicksort(arr):
"""Sorts the array in-place using quicksort algorithm."""
_quicksort(arr, 0, len(arr)-1)
and not return anything.
Then the user must do:
code
a = [3,2,1]
quicksort(a)
print(a) # [1,2,3]
That's like a.sort().
So I think it's acceptable.
Let me do that.
Final code without return:
import random
def quicksort(arr):
"""Sorts the array in-place using quicksort with random pivot."""
_quicksort(arr, 0, len(arr)-1)
def _quicksort(arr, low, high):
if low < high:
pi = partition(arr, low, high)
_quicksort(arr, low, pi-1)
_quicksort(arr, pi+1, high)
def partition(arr, low, high):
pivot_idx = random.randint(low, high)
arr[pivot_idx], arr[high] = arr[high], arr[pivot_idx]
pivot = arr[high]
i = low - 1
for j in range(low, high):
if arr[j] <= pivot:
i += 1
arr[i], arr[j] = arr[j], arr[i]
arr[i+1], arr[high] = arr[high], arr[i+1]
return i+1
That's it.
However, note that the function quicksort will work for any list of comparable elements.
But if the list contains non-comparable elements, it will throw an error.
That's expected.
Let me test with a small example:
code
a = [3, 1, 2]
quicksort(a)
print(a) # [1,2,3]
It should work.
But note: the random pivot might cause different partitions, but the result should be sorted.
I think it's correct.
We are done.
However, the problem says "in a language of your choice", and I chose Python.
So the above is the implementation.
But note: the problem might be expecting a non-in-place version? The problem doesn't specify.
Since the classic quicksort is in-place, I think it's acceptable.
If we want a non-in-place version, we can do:
code
def quicksort(arr):
if len(arr) <= 1:
return arr
pivot = arr[-1]
left = [x for x in arr[:-1] if x <= pivot]
right = [x for x in arr[:-1] if x > pivot]
return quicksort(left) + [pivot] + quicksort(right)
But this uses extra memory and is not in-place.
Since the problem doesn't specify, I'll stick to in-place.
But note: the in-place version is more efficient in terms of space.
So I think it's better.
However, the non-in-place version is easier to understand.
But the problem says "implement the quicksort algorithm", and the algorithm is usually described as in-place.
I think in-place is the way to go.
So I'll submit the in-place version.
But note: the in-place version we wrote uses random pivot and Lomuto partition.
That's acceptable.
Let me write the code again without the comments for the final answer.
However, the problem might require a specific pivot selection? It doesn't.
I think it's fine.
I'll write the code as above.
But note: the function _quicksort and partition are helper functions and should not be called directly.
We can put them inside quicksort? But then recursion would be tricky because we need to call the helper.
Alternatively, we can define them inside and then use a closure, but that's not necessary.
I'll leave them as separate functions with underscore.
Now, let's write the code in the answer.
However, the problem says "in a language of your choice", so I'll write in Python.
I think that's it.
I'll implement quicksort in Python with both in-place and functional versions, using the Lomuto partition scheme with random pivot selection to avoid worst-case performance on already-sorted arrays.
Implementation
python
import random
from typing import List, Any
def quicksort_inplace(arr: List[Any], low: int = 0, high: int = None) -> None:
"""
In-place quicksort using Lomuto partition scheme with random pivot.
Modifies the input list directly.
"""
if high is None:
high = len(arr) - 1
if low < high:
# Partition the array and get pivot index
pivot_index = partition(arr, low, high)
# Recursively sort elements before and after partition
quicksort_inplace(arr, low, pivot_index - 1)
quicksort_inplace(arr, pivot_index + 1, high)
def partition(arr: List[Any], low: int, high: int) -> int:
"""
Lomuto partition scheme:
1. Randomly select pivot and swap with last element
2. Partition array so that elements <= pivot are on left
3. Return final position of pivot
"""
# Random pivot selection to avoid worst-case O(n²) on sorted arrays
pivot_idx = random.randint(low, high)
arr[pivot_idx], arr[high] = arr[high], arr[pivot_idx]
pivot = arr[high]
i = low - 1 # Index of smaller element
for j in range(low, high):
if arr[j] <= pivot:
i += 1
arr[i], arr[j] = arr[j], arr[i]
# Place pivot in correct position
arr[i + 1], arr[high] = arr[high], arr[i + 1]
return i + 1
def quicksort_functional(arr: List[Any]) -> List[Any]:
"""
Functional (non-mutating) version that returns a new sorted list.
Uses list comprehensions for clarity.
"""
if len(arr) <= 1:
return arr
# Choose pivot (using last element for simplicity)
pivot = arr[-1]
# Partition using list comprehensions
left = [x for x in arr[:-1] if x <= pivot]
right = [x for x in arr[:-1] if x > pivot]
# Recursively sort partitions and combine
return quicksort_functional(left) + [pivot] + quicksort_functional(right)
# Helper function for easy usage
def quicksort(arr: List[Any], inplace: bool = True) -> List[Any]:
"""
Main interface function.
Args:
arr: List to sort
inplace: If True, sorts in-place and returns None.
If False, returns a new sorted list.
Returns:
Sorted list if inplace=False, otherwise None.
"""
if inplace:
quicksort_inplace(arr)
return arr
else:
return quicksort_functional(arr)
Example Usage
python
# Example 1: In-place sorting (modifies original list)
data = [3, 6, 8, 10, 1, 2, 1]
print("Original:", data)
quicksort(data) # Sorts in-place
print("Sorted in-place:", data)
# Example 2: Functional version (returns new list)
data2 = [5, 2, 9, 1, 5, 6]
sorted_data = quicksort(data2, inplace=False)
print("Original:", data2)
print("New sorted list:", sorted_data)
# Example 3: Edge cases
empty = []
quicksort(empty)
print("Empty list:", empty)
single = [42]
quicksort(single)
print("Single element:", single)
# Example 4: Sorting strings
words = ["banana", "apple", "cherry", "date"]
quicksort(words)
print("Sorted strings:", words)
Key Features:
Random Pivot Selection: Avoids O(n²) worst-case on already-sorted arrays
Two Interfaces:
quicksort_inplace(): Modifies list in-place (space-efficient)
quicksort_functional(): Returns new sorted list (immutable)
Lomuto Partition Scheme: Simple implementation with clear partitioning logic
Type Hints: Better code documentation
Handles Edge Cases: Empty lists, single elements, duplicates
Time & Space Complexity:
Average Case: O(n log n)
Worst Case: O(n²) (very unlikely with random pivot)
Space Complexity:
In-place: O(log n) for recursion stack
Functional: O(n) for new lists + O(log n) recursion
Why This Implementation?
Random pivot makes it robust for real-world data
In-place version is memory efficient (only O(log n) extra space)
Functional version is safer when you need to preserve original data
Clear separation of partition logic from recursion
Pythonic with list comprehensions in functional version
This implementation balances efficiency, readability, and practical usefulness for different scenarios.