using System;
class QuickSort {
// Function to swap two elements in array
static void Swap(int[] arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
// Partition function to place pivot correctly
static int Partition(int[] arr, int low, int high) {
int pivot = arr[high]; // pivot is last element
int i = low - 1; // index of smaller element
for (int j = low; j < high; j++) {
if (arr[j] <= pivot) {
i++;
Swap(arr, i, j); // move smaller element to left
}
}
Swap(arr, i + 1, high); // place pivot after smaller elements
return i + 1; // return pivot index
}
// QuickSort recursive function
static void QuickSortRecursive(int[] arr, int low, int high) {
if (low < high) {
int pi = Partition(arr, low, high); // partition array
QuickSortRecursive(arr, low, pi - 1); // sort left part
QuickSortRecursive(arr, pi + 1, high); // sort right part
}
}
// Driver function
static void Main() {
int[] arr = {7, 2, 9, 4, 3};
QuickSortRecursive(arr, 0, arr.Length - 1);
// Print sorted array
for (int i = 0; i < arr.Length; i++) {
Console.Write(arr[i]);
if (i < arr.Length - 1) Console.Write(", ");
}
Console.WriteLine();
}
}int pivot = arr[high]; // pivot is last element
select pivot to divide array
for (int j = low; j < high; j++) { if (arr[j] <= pivot) { i++; Swap(arr, i, j); } }
move elements smaller or equal to pivot to left side
Swap(arr, i + 1, high); return i + 1;
place pivot in correct position and return its index
if (low < high) { int pi = Partition(arr, low, high); QuickSortRecursive(arr, low, pi - 1); QuickSortRecursive(arr, pi + 1, high); }
recursively sort left and right parts around pivot