Quick Sort Program in Java Taking First Element as Pivot

Java program for quick sort. Quicksort is a programming language written in Java. It works by picking a ‘pivot’ element from the array and partitioning the remaining elements into two subarrays based on whether they are  greater or less than the pivot.

Java Program for Quick Sort With Example

Quicksort is a sorting algorithm that uses the divide-and-conquer concept to sort data. It has an average complexity of O(n log n) and is one of the most popular sorting algorithms, especially for large data sets.

A sorting approach that divides a list into two pieces and moves the lower items to one side and the higher ones to the other to sequence it. It begins by selecting one item from the full list as the pivot point. The pivot could be the initial object or one selected at random.

Pivot Element in Java Program

The “pivot element” is the name given to this element. Select the element in the middle of the array, for example. All elements less than the pivot element are placed in one array, while all elements larger than the pivot element are placed in another. Recursively apply Quicksort to both arrays to sort them.

import java.util.Arrays;
class Main 
int a(int array[], int low, int high)
int pivot = array[high];
int i = (low - 1);
for (int j = low; j < high; j++) 
if (array[j] <= pivot)
int temp = array[i];
array[i] = array[j];
array[j] = temp;
int temp = array[i + 1];
array[i + 1] = array[high];
array[high] = temp;
return (i + 1);
void quickSort(int array[], int low, int high) {
if (low < high) 
int pi = a(array, low, high);
quickSort(array, low, pi - 1);
quickSort(array, pi + 1, high);
public static void main(String args[]) 
int[] data = { 56,787,343,456,987,111};
int size = data.length;
Main qs = new Main();
qs.quickSort(data, 0, size - 1);
System.out.println("After sorting");


After sorting   
[56, 111, 343, 456, 787, 987]