public class QuickSort {
// Function to swap two elements in the array
private 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
private static int partition(int[] arr, int low, int high) {
int pivot = arr[high]; // choose last element as pivot
int i = low - 1; // index of smaller element
for (int j = low; j < high; j++) {
if (arr[j] <= pivot) {
i++; // move smaller element index forward
swap(arr, i, j); // swap smaller element to correct position
}
}
swap(arr, i + 1, high); // place pivot after smaller elements
return i + 1; // return pivot index
}
// QuickSort recursive function
public static void quickSort(int[] arr, int low, int high) {
if (low < high) {
int pi = partition(arr, low, high); // partition array
quickSort(arr, low, pi - 1); // sort left part
quickSort(arr, pi + 1, high); // sort right part
}
}
// Driver code
public static void main(String[] args) {
int[] arr = {7, 2, 9, 4, 3};
quickSort(arr, 0, arr.length - 1);
for (int num : arr) {
System.out.print(num + " ");
}
}
}
int pivot = arr[high]; // choose last element as pivot
select pivot to divide array
for (int j = low; j < high; j++) { if (arr[j] <= pivot) { i++; swap(arr, i, j); } }
move elements smaller than pivot to left side
swap(arr, i + 1, high); return i + 1;
place pivot in correct sorted position
if (low < high) { int pi = partition(arr, low, high); quickSort(arr, low, pi - 1); quickSort(arr, pi + 1, high); }
recursively sort left and right parts