Data Structures and Algorithms • C# examples
Quicksort and Partitioning
Partition values around a pivot and recursively sort the resulting regions.
Concept
Quicksort is an in-place divide-and-conquer sort in common implementations. Its performance depends on pivot choices and partition behavior: balanced partitions give O(n log n), while repeatedly poor partitions can degrade to O(n²). Randomized pivots reduce predictable adversarial patterns but do not change the worst-case bound.
How to approach it
Define whether the pivot belongs to the left or right partition, maintain that invariant, and recurse only on smaller ranges.
Complexity
Average O(n log n), worst O(n²); stack space depends on partition balance.
C# example
static int Partition(int[] values, int low, int high)
{
int pivot = values[high], boundary = low;
for (int scan = low; scan < high; scan++)
if (values[scan] <= pivot)
(values[boundary], values[scan], boundary) =
(values[scan], values[boundary], boundary + 1);
(values[boundary], values[high]) = (values[high], values[boundary]);
return boundary;
}
Expected result or behavior
After partitioning, values on the left are no greater than the pivot and values on the right are greater.
Practice exercise
Choose a pivot strategy and test all-equal, sorted, and reverse-sorted arrays.
Key takeaway: Partition invariants and pivot strategy determine practical and worst-case behavior.