public class QuickSort {
public static void main(String[] args) {
int arr[] = {1,12,9,14,16,80,33,3,4,7,60,2};
System.out.println("printing an array");
printArray(arr);
quickSort(arr,0,arr.length-1);
System.out.println("printing a sorted array");
printArray(arr);
}
static void printArray(int arr[])
{
int n = arr.length;
for (int i = 0; i < n; ++i)
System.out.print(arr[i] + " ");
System.out.println();
}
static void quickSort(int arr[], int lowIndex, int highIndex){
if(lowIndex<highIndex){
int midIndex = partition(arr,lowIndex,highIndex);
System.out.println("partition array lowIndex::"+lowIndex+", highIndex::"+highIndex);
printArray(arr);
quickSort(arr,lowIndex,midIndex-1);
quickSort(arr,midIndex+1,highIndex);
}
}
static int partition(int arr[],int lowIndex, int highIndex){
int pivot = arr[highIndex];
int i = lowIndex-1;
for(int j=lowIndex;j<=highIndex-1;j++){
if(arr[j]<pivot){
i++;
swap(arr,i,j);
}
}
swap(arr,i+1,highIndex);
return i+1;
}
static void swap(int arr[], int i, int j){
int temp = arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
}
Output :
printing an array 1 12 9 14 16 80 33 3 4 7 60 2 partition array lowIndex::0, highIndex::11 1 2 9 14 16 80 33 3 4 7 60 12 partition array lowIndex::2, highIndex::11 1 2 9 3 4 7 12 14 16 80 60 33 partition array lowIndex::2, highIndex::5 1 2 3 4 7 9 12 14 16 80 60 33 partition array lowIndex::2, highIndex::3 1 2 3 4 7 9 12 14 16 80 60 33 partition array lowIndex::7, highIndex::11 1 2 3 4 7 9 12 14 16 33 60 80 partition array lowIndex::7, highIndex::8 1 2 3 4 7 9 12 14 16 33 60 80 partition array lowIndex::10, highIndex::11 1 2 3 4 7 9 12 14 16 33 60 80 printing a sorted array 1 2 3 4 7 9 12 14 16 33 60 80