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 temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } int temp1 = arr[i + 1]; arr[i + 1] = arr[high]; arr[high] = temp1; return i + 1; } int[] array = {9, 3, 7, 6, 2, 8, 5}; int pivotIndex = Partition(array, 0, array.Length - 1); Console.WriteLine(string.Join(", ", array));
The partition function moves all elements smaller than the pivot (5) to the left. The pivot ends up at index 4. The array after partition is [3, 2, 1, 5, 6, 8, 9].
After partition, the pivot is placed correctly. Quick Sort then sorts elements left of pivot and right of pivot separately. Here, those are [1, 3] and [7].
int Partition(int[] arr, int low, int high) { int pivot = arr[low]; int i = low + 1; int j = high; while (true) { while (i <= j && arr[i] <= pivot) i++; while (j >= i && arr[j] > pivot) j--; if (i >= j) break; int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } int temp2 = arr[low]; arr[low] = arr[j]; arr[j] = temp2; return j; } int[] array = {5, 2, 9, 1}; int p = Partition(array, 0, array.Length - 1); Console.WriteLine(string.Join(", ", array));
The inner loops can cause i to move beyond array bounds or get stuck if conditions are not properly checked, causing an infinite loop.
void QuickSort(int[] arr, int low, int high) { if (low < high) { int pi = Partition(arr, low, high); QuickSort(arr, low, pi - 1); QuickSort(arr, pi + 1, high); } } 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 temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } int temp1 = arr[i + 1]; arr[i + 1] = arr[high]; arr[high] = temp1; return i + 1; } int[] array = {10, 7, 8, 9, 1, 5}; QuickSort(array, 0, array.Length - 1); Console.WriteLine(string.Join(", ", array));
Quick Sort with Lomuto partition sorts the array fully in ascending order: [1, 5, 7, 8, 9, 10].
The worst case happens when the pivot is the smallest or largest element every time, causing unbalanced partitions and O(n^2) time.
