Example output
Alright, let's dive into Quicksort!
Quicksort is a "divide and conquer" sorting algorithm, which means it breaks the problem into smaller subproblems and solves each one independently. This allows it to sort an array of items efficiently. Its average time complexity is O(n log n), but it can degrade to O(n^2) if the pivot is always chosen as the first or last element of the sorted array.
Here's how the algorithm works:
1. **Selection of Pivot:** The first step is to choose a "pivot" from the array. Different pivot selection strategies exist, but for simplicity, let's say we always choose the last element of the array. The choice of pivot affects the efficiency of Quicksort, as a "good" pivot will split the array into two roughly equal parts.
2. **Partitioning:** The array is then rearranged so that all elements less than the pivot are to its left, and all elements greater are to its right. The pivot is now in its final sorted position.
3. **Recursive sort:** Steps 1 and 2 are repeated recursively for the left and right partitions (excluding the pivot), until the base case of an empty or single-element array is reached.
Let's see this in Python code:
```python
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
def quicksort(arr, low, high):
if low < high:
pi = partition(arr, low, high)
quicksort(arr, low, pi-1)
quicksort(arr, pi+1, high)
# Driver code
arr = [10, 7, 8, 9, 1, 5]
n = len(arr)
quicksort(arr, 0, n-1)
print("Sorted array is:", arr)
```
In the code above, `partition` is a helper function that selects the pivot and partitions the array. `quicksort` is the main function that implements the divide-and-conquer logic via recursion.
The choice of pivot is crucial. If you always choose the smallest or largest element as the pivot, the performance degrades to O(n^2) as it results in an unbalanced partition. On the other hand, if you can always choose the median as the pivot, the algorithm performs optimally with O(n log n) complexity. However, finding the median itself is an O(n) operation, which defeats the purpose. Hence, in practice, a reasonable approach could be to pick a random element as the pivot.
I hope this gives you a better understanding of Quicksort. Feel free to ask if you have more questions!