// Function to perform the partitioning step of Quick Sort
int partition(int arr[], int low, int high) { // Choosing the last element as the pivot int pivot = arr[high]; int i = (low - 1); // Index of smaller element
// Rearranging elements based on the pivot
for (int j = low; j <= high - 1; j++) { // If current element is smaller than or equal to the pivot if (arr[j] <= pivot) { i++; // Increment index of smaller element swap(arr[i], arr[j]); // Swap arr[i] and arr[j] } } // Place the pivot in its correct position swap(arr[i + 1], arr[high]); return (i + 1); // Return the index of the pivot }
// Quick Sort function (recursive)
void quickSort(int arr[], int low, int high) { if (low < high) { // Find pivot index int pi = partition(arr, low, high);
// Recursively sort the elements before and after the pivot
quickSort(arr, low, pi - 1); // Before pivot quickSort(arr, pi + 1, high); // After pivot } }
// Function to print the array
void printArray(int arr[], int size) { for (int i = 0; i < size; i++) { cout << arr[i] << " "; } cout << endl; }
int main() { // Example array int arr[] = {10, 7, 8, 9, 1, 5}; int n = sizeof(arr) / sizeof(arr[0]);