Below is an efficient implementation of the Quick Sort algorithm in Python. Quick Sort is a divide-and-conquer algorithm with an average time complexity of O(n log n), making it suitable for sorting large datasets. However, its worst-case time complexity is O(n^2) if the pivot is chosen poorly (e.g., in a already sorted array). To mitigate this, the implementation below uses the last element as the pivot by default, which works well for most cases.
The code sorts the array in place to save space (no additional arrays are created). I've included comments for clarity and a simple example at the end.
Code:
def partition(arr, low, high):
"""
Partition the array around a pivot element.
This function rearranges the array such that:
- All elements less than or equal to the pivot are on the left of the pivot.
- All elements greater than the pivot are on the right.
Args:
arr (list): The array to partition.
low (int): The starting index of the subarray.
high (int): The ending index of the subarray.
Returns:
int: The final index of the pivot element.
"""
pivot = arr[high] # Choose the last element as the pivot
i = low - 1 # Index of the smaller element
for j in range(low, high):
if arr[j] <= pivot:
i += 1 # Increment index of smaller element
arr[i], arr[j] = arr[j], arr[i] # Swap elements
arr[i + 1], arr[high] = arr[high], arr[i + 1] # Swap pivot to its correct position
return i + 1 # Return the pivot index
def quick_sort(arr, low, high):
"""
The main Quick Sort function that sorts the array recursively.
Args:
arr (list): The array to sort.
low (int): The starting index of the subarray.
high (int): The ending index of the subarray.
"""
if low < high:
pi = partition(arr, low, high) # Get the partition index
quick_sort(arr, low, pi - 1) # Recursively sort the left subarray
quick_sort(arr, pi + 1, high) # Recursively sort the right subarray
def quicksort(arr):
"""
Wrapper function to sort the entire array.
Args:
arr (list): The array to sort.
This function sorts the array in place.
"""
if len(arr) > 1:
quick_sort(arr, 0, len(arr) - 1)
# Example usage:
if __name__ == "__main__":
unsorted_array = [10, 7, 8, 9, 1, 5, 3, 4, 6, 2]
print("Original array:", unsorted_array)
quicksort(unsorted_array) # Sort in place
print("Sorted array:", unsorted_array)
Explanation:
- Partition Function: This is the core of Quick Sort. It selects a pivot (here, the last element) and rearranges the array so that elements less than or equal to the pivot are on the left, and elements greater are on the right. This takes O(n) time for each partition.
- Quick Sort Function: This recursively applies the partition to the subarrays on the left and right of the pivot.
- Wrapper Function:
quicksort(arr) is a simple interface to sort the entire array. It calls the recursive helper function.
- Efficiency:
- Time Complexity: Average: O(n log n), Worst: O(n^2) (e.g., if the array is sorted and the pivot is always the smallest/largest element).
- Space Complexity: O(log n) on average due to the recursion stack (though it can go up to O(n) in the worst case for skewed partitions).
- To improve worst-case performance, you could randomize the pivot selection (e.g., by swapping a random element with the last one before partitioning). If you'd like that added, let me know!
Output Example:
When you run the code, the output will be:
Original array: [10, 7, 8, 9, 1, 5, 3, 4, 6, 2]
Sorted array: [1, 3, 4, 5, 6, 7, 8, 9, 10]
This implementation is straightforward, efficient for most practical use cases, and handles edge cases like empty arrays or single-element arrays gracefully. If you need any modifications (e.g., randomized pivot or handling duplicates), just ask!