The user wants an implementation of the quicksort algorithm.
I need to choose a programming language. Python is generally a good choice because it's readable and widely understood.
I need to decide on the specific implementation style. There are two main ways:
The "Pythonic" way using list comprehensions (easy to read, but not in-place).
The "Classic" way using partitioning and recursion (in-place, more memory efficient).
Since the user just asked for "the quicksort algorithm," providing the in-place version is usually more valuable for understanding the actual algorithmic mechanics, but the list comprehension version is very popular in Python contexts. I will provide the in-place version as the primary answer because it represents the standard algorithm better (O(log n) space complexity vs O(n) for the list copy version). I might briefly mention the simple version or just stick to the standard one to keep it clean. Let's stick to the standard in-place version but keep the code clean.
Plan:
Define the language (Python).
Write the main quicksort function.
Write the helper partition function.
Choose a pivot (e.g., the last element).
Iterate through the sub-array.
Swap elements smaller than the pivot to the left.
Place the pivot in its correct sorted position.
Implement the recursion in quicksort.
Base case: low index < high index.
Call partition.
Recursively sort left part.
Recursively sort right part.
Add example usage.
Add comments explaining the steps.
Briefly explain the Time Complexity.
Refining the implementation:
Function signature:quicksort(arr, low, high)
Partition:
pivot = arr[high]
i = low - 1 (index of smaller element)
Loop j from low to high - 1.
If arr[j] <= pivot:
i += 1
Swap arr[i], arr[j]
Swap arr[i+1], arr[high] (put pivot in place)
Return i + 1
Alternative:
I could write a wrapper function sort(arr) that calls quicksort(arr, 0, len(arr)-1) to make it easier to call. This is a nice UX touch.
Let's write the Python code mentally:
python
def partition(array, low, high):
pivot = array[high]
i = low - 1
for j in range(low, high):
if array[j] <= pivot:
i += 1
array[i], array[j] = array[j], array[i]
array[i+1], array[high] = array[high], array[i+1]
return i + 1
def quicksort(array, low, high):
if low < high:
pi = partition(array, low, high)
quicksort(array, low, pi - 1)
quicksort(array, pi + 1, high)
Another option:
I could provide the "easy" version first, as it's 3 lines long, then the "efficient" version.
Actually, strictly speaking, the 3-line version isn't "QuickSort" in the academic sense (in-place partitioning), it's just a recursive sort. The prompt asks for "the quicksort algorithm," which implies the Hoare/Lomuto partition scheme. I will stick to the in-place version.
Final Polish:
I will provide the code in Python.
I will include an example driver code block.
I will add a brief explanation of how the pivot and partitioning work.
Let's check for edge cases in the code.
Empty array: low (0) is not less than high (-1). Returns immediately. Correct.
Single element: low (0) is not less than high (0). Returns immediately. Correct.
The code looks solid. I will present it clearly.
Wait, what about the language choice?
Python is good. C++ is also good but more verbose. Java is okay. JavaScript is fine. Python is the safest bet for general readability.
Let's stick to Python.
Structure of the response:
Brief intro.
The Code (Python).
Explanation of the logic (Pivot, Partition, Recursion).
Time Complexity note.
Here is an implementation of the Quicksort algorithm in Python.
This implementation uses the standard "in-place" approach (specifically the Lomuto partition scheme), which means it sorts the array without creating new lists, making it memory efficient.
Python Implementation
python
def partition(array, low, high):
"""
This function takes the last element as the pivot, places
the pivot element at its correct position in the sorted array,
and places all smaller elements to the left of the pivot
and all larger elements to the right.
"""
pivot = array[high]
# Pointer for the greater element
i = low - 1
# Traverse through all elements and compare with pivot
for j in range(low, high):
if array[j] <= pivot:
# If element smaller than pivot is found, swap it with the
# element pointed by i
i += 1
array[i], array[j] = array[j], array[i]
# Swap the pivot element with the greater element specified by i
array[i + 1], array[high] = array[high], array[i + 1]
# Return the position from where the partition is done
return i + 1
def quicksort(array, low, high):
"""
The main function that implements QuickSort.
"""
if low < high:
# Find pivot element such that
# elements smaller than pivot are on the left
# elements greater than pivot are on the right
pi = partition(array, low, high)
# Recursive call on the left of pivot
quicksort(array, low, pi - 1)
# Recursive call on the right of pivot
quicksort(array, pi + 1, high)
# --- Driver Code ---
if __name__ == '__main__':
data = [8, 7, 2, 1, 0, 9, 6]
size = len(data)
print("Unsorted Array:")
print(data)
quicksort(data, 0, size - 1)
print("\nSorted Array in Ascending Order:")
print(data)
How it works:
Pivot Selection: In this implementation, we select the last element of the array as the pivot (array[high]).
Partitioning: The partition function rearranges the array so that all elements less than or equal to the pivot come before it, and all elements greater come after it. The pivot is then swapped into its final correct sorted position.
Recursion: The quicksort function calls itself recursively for the sub-array to the left of the pivot and the sub-array to the right of the pivot.
Base Case: The recursion stops when low is no longer less than high, meaning the sub-array has 0 or 1 element and is therefore already sorted.
Performance:
Time Complexity:
Best/Average Case:O(nlogn)
Worst Case:O(n2) (This happens if the pivot is always the smallest or largest element, e.g., sorting an already sorted array).
Space Complexity:O due to the recursive stack frames.