int[] arr = {8, 3, 7, 6, 2}; int LomutoPartition(int[] array, int low, int high) { int pivot = array[high]; int i = low - 1; for (int j = low; j < high; j++) { if (array[j] <= pivot) { i++; int temp = array[i]; array[i] = array[j]; array[j] = temp; } } int temp1 = array[i + 1]; array[i + 1] = array[high]; array[high] = temp1; return i + 1; } int p = LomutoPartition(arr, 0, arr.Length - 1); // Print array after partition string result = string.Join(", ", arr);
Remember Lomuto partition places elements smaller or equal to pivot to the left and pivot at the correct position.
Lomuto partition selects the last element as pivot (2). No elements <= 2 before it, so i remains -1 and pivot swaps to front. The final array after partition is [2, 3, 7, 6, 8].
int[] arr = {8, 3, 7, 6, 2}; int HoarePartition(int[] array, int low, int high) { int pivot = array[low]; int i = low - 1; int j = high + 1; while (true) { do { i++; } while (array[i] < pivot); do { j--; } while (array[j] > pivot); if (i >= j) return j; int temp = array[i]; array[i] = array[j]; array[j] = temp; } } int p = HoarePartition(arr, 0, arr.Length - 1); // Print array after partition string result = string.Join(", ", arr);
Hoare partition uses the first element as pivot and swaps elements to ensure left side smaller and right side larger.
Hoare partition selects 8 as pivot. It swaps elements to place smaller on left and larger on right. The final array after partition is [2, 3, 7, 6, 8].
Think about where the pivot ends up after partition in each scheme.
Lomuto partition places the pivot at its correct sorted position after partition. Hoare partition only ensures elements are partitioned but pivot may not be at final position.
Check the initialization of i and how it is incremented inside the loop.
Starting i at low and incrementing after swap is a valid Lomuto variant. The code runs correctly and partitions the array.
Consider if pivot is smallest element in the array.
Hoare partition does not guarantee any minimum number of items in left partition. If pivot is smallest, left partition can be empty.
