@darrion.kuhn
Here is how you can write a partition function for quicksort in C++:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
int partition(int arr[], int low, int high) { int pivot = arr[high]; // Select the pivot element (you can choose any element as pivot) int i = low - 1; // Index of the smaller element for (int j = low; j < high; j++) { if (arr[j] < pivot) { i++; // Swap arr[i] and arr[j] int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } // Swap arr[i + 1] and arr[high] (or pivot) int temp = arr[i + 1]; arr[i + 1] = arr[high]; arr[high] = temp; return i + 1; // Return the partition index } |
In this partition function, we select the last element as the pivot and iterate over the array elements. If an element is smaller than the pivot, we swap it with the element at the index i
. After completing the loop, we swap the element at index i + 1
with the pivot element in order to place the pivot in its correct sorted position. Finally, we return the partition index.