The user wants a program that implements the Quicksort algorithm.
Specifically, the pivot selection must be random.
I need to decide which programming language to use.
Python is a standard choice for algorithm demonstration due to readability.
C++ is also good for performance, but Python is often easier for general understanding.
I'll provide the solution in Python, but maybe I should add C++ or Java if I want to be thorough? Let's stick to Python as the primary example because it's pseudocode-like, but I'll make sure it's clear and follows standard partitioning schemes (Lomuto or Hoare).
Let's break down the Quicksort algorithm with random pivot:
Base Case: If the list has 0 or 1 elements, it's already sorted.
Pivot Selection: Choose a random element from the current sub-array.
Partitioning: Rearrange the array so that elements less than the pivot are on the left, and elements greater are on the right.
Recursion: Apply Quicksort to the left part and the right part.
Partitioning Schemes:
Lomuto Partition: Picks the last element as pivot. Since we need a random pivot, we swap the random element with the last element, then run the standard Lomuto procedure. This is easier to implement.
Hoare Partition: Picks the first element as pivot (usually). Two pointers start at ends and move inward. This is generally more efficient (fewer swaps) but slightly trickier to get right with duplicate elements or edge cases.
I will use the Lomuto partition scheme because it's more intuitive for beginners, but I will add the random swap step.
Step-by-Step Implementation Plan (Python):
Import random.
Define function quicksort(arr, low, high).
Define helper function partition(arr, low, high).
Inside partition:
Pick random index i between low and high.
Swap arr[i] with arr[high]. (Now the random pivot is at the end).
Proceed with standard Lomuto logic: pivot = arr[high], iterate j from low to high-1.
Inside quicksort:
Check low < high.
Call partition to get pi (pivot index).
Recurse quicksort(arr, low, pi - 1).
Recurse quicksort(arr, pi + 1, high).
Alternative: Pythonic approach (List Comprehension):
This is often requested in Python specific contexts.
qsort(arr) = qsort([x for x in arr[1:] if x < pivot]) + [pivot] + qsort([x for x in arr[1:] if x >= pivot])
However, this creates new lists and uses extra O(N) space. The in-place version is usually what is expected when asking for an "implementation of Quicksort" in a CS context. I will provide the in-place version as the primary answer because it reflects the standard algorithm better, but I might mention the Pythonic one or just stick to the strict in-place version to be unambiguous.
Let's write the code for the in-place version.
Drafting Code:
python
import random
def partition(arr, low, high):
# Random pivot selection
rand_index = random.randint(low, high)
arr[high], arr[rand_index] = arr[rand_index], arr[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)
Wait, usually quicksort is called with just the array in user-land. I should provide a wrapper function sort(arr) that calls quicksort(arr, 0, len(arr)-1).
Refining the explanation:
Explain the logic (Divide and Conquer).
Explain the "Random" part (Swap random element with the end to use standard Lomuto).
Provide the code.
Provide an example usage.
Briefly mention Time Complexity (O(NlogN) average, O(N2) worst case but randomized makes worst case rare).
Let's double check the random index range.
Python's random.randint(a, b) is inclusive. So randint(low, high) is correct.
What if I provided a C++ version too? It's helpful for students. The prompt didn't specify language. I'll stick to Python as default but make the code clean. Actually, offering C++ is a nice value-add. I'll provide Python and C++.
C++ Implementation Plan:
Include <iostream>, <vector>, <cstdlib>, <ctime>, <algorithm>.
Function partition(vector<int>&, int low, int high).
Random logic: int random = low + rand() % (high - low + 1). Swap arr[random] with arr[high].
Standard Lomuto.
quickSort function.
Okay, I will focus on the Python implementation as the main answer because it's the most readable pseudo-code-like language, and add the C++ implementation as an alternative for strictly typed preference.
Structure of response:
Python Code (Complete, runnable, in-place).
Explanation of the Random Pivot Strategy (Why swap to the end?).
Example Usage.
(Optional but good) C++ Code.
Let's stick to just Python to keep it simple unless the user asked for more, but usually, algorithm questions imply "show me the logic". Python is best for logic. I'll write the Python solution and explain it clearly.
Code check:
python
import random
def partition(array, low, high):
# 1. Select random pivot
pivot_index = random.randint(low, high)
# 2. Swap with the last element to use standard Lomuto partitioning
array[high], array[pivot_index] = array[pivot_index], array[high]
pivot = array[high]
# 3. Pointer for the greater element
i = low - 1
# 4. Traverse through all elements
# compare each element with pivot
for j in range(low, high):
if array[j] <= pivot:
# If element smaller than pivot is found
# swap it with the greater element pointed by i
i = i + 1
(array[i], array[j]) = (array[j], array[i])
# 5. 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 partition is done
return i + 1
def quick_sort(array, low, high):
if low < high:
# Find pivot element such that
# element smaller than pivot are on the left
# element greater than pivot are on the right
pi = partition(array, low, high)
# Recursive call on the left of pivot
quick_sort(array, low, pi - 1)
# Recursive call on the right of pivot
quick_sort(array, pi + 1, high)
This looks correct. I will wrap this in a nice class or helper function for the user to run easily.
Wait, Lomuto partition loops range(low, high) (excluding high). Since we swapped the pivot to high, this is correct.
Loop invariant: arr[low...i] are elements <= pivot. arr[i+1...j-1] are elements > pivot. arr[j...high-1] are unchecked. arr[high] is pivot.
If arr[j] <= pivot, increment i, swap arr[i] and arr[j].
Finally swap arr[i+1] and arr[high].
Correct.
I will format the output clearly.
Intro.
Python Implementation.
Explanation of how it works.
Complexity analysis (brief).
I will also include a driver code block so they can just copy-paste and run.
Let's consider Hoare partition again. It is better.
Hoare with random pivot:
Pick random index. Swap with low.
i = low - 1, j = high + 1.
while True: i+=1 while arr[i]<pivot, j-=1 while arr[j]>pivot, if i>=j return j, swap arr[i], arr[j].
It's slightly more error prone to write off the cuff for beginners (e.g. handling duplicates requires strict < and >, loop conditions).
Lomuto is standard for teaching. I'll stick to Lomuto.
Final check on random.randint(low, high).
If low = 0, high = 1. It generates 0 or 1. Correct.
One detail: The user might want the function signature to be just quicksort(arr).
I will provide quick_sort(arr, low, high) and a wrapper sort_array(arr).
Ready to generate.
Here is a standard implementation of Quicksort in Python using the Lomuto partition scheme.
This implementation selects a random element as the pivot, swaps it to the end of the array (to handle it easily), and then proceeds with the standard partitioning logic.
Python Implementation
python
import random
def partition(arr, low, high):
# 1. Select a random pivot index between low and high
pivot_index = random.randint(low, high)
# 2. Swap the pivot element with the last element
# This allows us to use the standard Lomuto partition logic
arr[pivot_index], arr[high] = arr[high], arr[pivot_index]
pivot = arr[high]
# 3. Partitioning logic
# i indicates the index of the smaller element
i = low - 1
for j in range(low, high):
# If current element is smaller than or equal to pivot
if arr[j] <= pivot:
i += 1
# Swap arr[i] and arr[j]
arr[i], arr[j] = arr[j], arr[i]
# 4. Place the pivot in the correct sorted position
# (swap arr[i+1] and arr[high])
arr[i + 1], arr[high] = arr[high], arr[i + 1]
# Return the index where the pivot landed
return i + 1
def quick_sort(arr, low, high):
if low < high:
# pi is the partitioning index
pi = partition(arr, low, high)
# Recursively sort elements before partition
quick_sort(arr, low, pi - 1)
# Recursively sort elements after partition
quick_sort(arr, pi + 1, high)
# Helper function to make calling it easier
def sort(array):
quick_sort(array, 0, len(array) - 1)
return array
# --- Example Usage ---
if __name__ == "__main__":
data = [10, 7, 8, 9, 1, 5, 34, 2, 99]
print("Unsorted Array:", data)
sort(data)
print("Sorted Array: ", data)
How it Works
Random Pivot Selection: We pick a random index using random.randint. This prevents the algorithm from hitting its worst-case performance (O(n2)) on already sorted arrays.
Swapping: Since the Lomuto scheme is designed to iterate through the array and check against the last element, we simply swap our randomly selected pivot with the element at the end of the array.
Partitioning: We iterate through the array. If a number is smaller than the pivot, we move it to the left side (using the index variable i).
Final Swap: After the loop, the pivot (currently at the end) is swapped into its correct sorted position (at i + 1).
Recursion: The function calls itself twice: once for the sub-array to the left of the pivot and once for the sub-array to the right.
Complexity
Time Complexity: O(NlogN) on average. With random pivot selection, the likelihood of the worst-case scenario is extremely low.
Space Complexity: O(logN) for the recursion stack.