Sorting
Quick Sort (Lomuto)
Choose the last item as a pivot, partition smaller values to its left, then recurse on the two sides.
Algorithm
Basic Implementation
basic.cs
using System;
class Program {
static void Main() {
int[] arr = new int[] { 4, 1, 5, 2, 3 };
QuickSort(arr, 0, arr.Length - 1);
PrintArray(arr);
}
static void PrintArray(int[] arr) {
Console.Write("[");
for (int i = 0; i < arr.Length; i++) {
if (i > 0) Console.Write(", ");
Console.Write(arr[i]);
}
Console.WriteLine("]");
}
static int Partition(int[] arr, int low, int high) {
int pivot = arr[high];
int i = low - 1;
for (int j = low; j < high; j++) {
if (arr[j] <= pivot) {
i++;
int tmp = arr[i]; arr[i] = arr[j]; arr[j] = tmp;
}
}
int swap = arr[i + 1]; arr[i + 1] = arr[high]; arr[high] = swap;
return i + 1;
}
static void QuickSort(int[] arr, int low, int high) {
if (low < high) {
int pivotIndex = Partition(arr, low, high);
QuickSort(arr, low, pivotIndex - 1);
QuickSort(arr, pivotIndex + 1, high);
}
}
}
Complexity
- Time: O(n^2) worst, O(n log n) average
- Space: O(log n) average call stack
- Stable: no
Implementation notes
- Keep the explicit algorithmic steps instead of calling a standard-library
Array.Sort. This checked-in replay shows each comparison and swap in the first partition, then summarizes the recursive calls on already-sorted sides. - The
int[]is a managed reference type, so swaps mutate the same array object without pointer arithmetic or manual free/GC control. Index bounds are still enforced at runtime, which keeps the partition indices visible during the replay instead of relying on unchecked pointer movement.
pivot
The final element is moved to the boundary between smaller and larger values.
partition
One scan rearranges the current range before the recursive calls.