Coders Packet

Sorting an array given by the user using Quicksort algorithm in JAVA

By Kartik Rakesh Khandelwal

QuickSort Program while taking a number of elements (i.e. size of the array) and each element as input from the user in JAVA.

The purpose is to sort the array (which is given by the user), using QuickSort Algorithm in JAVA.

The sorting algorithm is an algorithm that puts elements of a list in a certain order.

Quicksort is a divide-and-conquer algorithm. It works by selecting a 'pivot' element from the array and partitioning the other elements into two sub-arrays, according to whether they are less than or greater than the pivot. 
On Average, the algorithm takes O(n log n) comparisons to sort n items.

import java.util.Arrays;
import java.util.Scanner;

class quickSort {

  int partition(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 quickSortFunction(int array[], int low, int high) {
    if (low < high) {

      int pi = partition(array, low, high);

      quickSortFunction(array, low, pi - 1);

      quickSortFunction(array, pi + 1, high);

  public static void main(String args[]) {

    Scanner sc = new Scanner(;
    System.out.print("Enter the number of elements:");
    int size = sc.nextInt();
    int[] data = new int[size];
    System.out.println("Enter elements:");
    for(int i=0 ; i

Quicksort Algorithm output

Download Complete Code


No comments yet