Thursday 9 November 2023

How to implement Quick Sort Alogrithm in Java

The quick sort partitions an array and then calls itself recursively twice to sort the resulting two subarray. This algorithm is quite efficient for large sized data sets as its average and worst case complexity are of O(nlogn) where n are no. of items


package in.jk.sort;

public class QuickSortApplication {

public int[] numbers = { 5, 1, 8, 3, 6, 7, 9, 4, 2, 10 };

public int partition(int left, int right) {

int pivot = numbers[right];
int leftPointer = left - 1;

for (int i = left; i <= right - 1; i++) {

if (numbers[i] < pivot) {
leftPointer++;
swap(leftPointer, i);
}
}

int leftPointerIncriment = leftPointer + 1;
swap(leftPointerIncriment, right);
return leftPointerIncriment;

}

public void quickSort(int left, int right) {

if (left < right) {
int parttion = this.partition(left, right);
quickSort(left, parttion - 1);
quickSort(parttion + 1, right);
}
}

public void swap(int left, int right) {

int temp = numbers[left];
numbers[left] = numbers[right];
numbers[right] = temp;
}

public static void main(String[] args) {

QuickSortApplication quickSortApplication = null;
                quickSortApplication =QuickSortApplication ();
int left = 0;
int right = quickSortApplication .numbers.length - 1;
quickSortApplication .quickSort(left, right);

System.out.println("Sorted Array :: ");
for (int element : quickSortApplication .numbers) {
System.out.print(element + " ");
}
}
}


Output :

Sorted Array :: 
1 2 3 4 5 6 7 8 9 10