How To Implement Quick Sort In Java Program

Sharing is healthy !!

Let us learn how to implement Quick sort in java program.

what is QUICKSORT?

By Quicksort, all of you know it is one of the fastest sorting algorithm.

Basically quicksort is a divide and conquer algorithm. At first this sort algorithm divides the given list into two divisions namely “divide” and “conquer”.

The first division is individually sorted and the second division is then combined and conquered.

Finally quicksort recursively sorts the above mentioned two divisions.

Let me take you through a code implementation,

example: How To Implement QUICK SORT In Java Program

```import java.util.Scanner;

public class How_To_Quick_Sort {         // class Quick sort

public static void Sort(int array[])     // function quick sort
{
quick_Sort(array, 0, array.length - 1);
}

public static void quick_Sort(int arr[], int small, int big){

int a = small;
int b = big;
int pivot = arr[(small + big) / 2];
int temp;

while(a <= b){
while(arr[a] < pivot)
a++;
while(arr[b] > pivot)
b--;
if(a <= b){                     // here swapping takes place
temp = arr[a];
arr[a] = arr[b];
rr[b] = temp;
a++;
b--;
}
}

if(small < b)             // sorting lower half using recursion
quick_Sort(arr, small, b);

if(a < big)
quick_Sort(arr, a, big);
}

// Main method starts here
public static void main(String[] args) {

Scanner sc = new Scanner(System.in);
System.out.println("Quick Sort In Java\n");
int x;
int y;

// Here we are accepting number of elements
System.out.println("Please enter few integer elements: ");
x = sc.nextInt();

// Here we are creating array
int array[] = new int[x];

// Here we are accepting x integer elements
System.out.println("\nPlease enter " + x + " integer elements");

for(y = 0;y < x;y++)
array[y] = sc.nextInt();

// Calling method sort
Sort(array);

// Printing sorted array
System.out.println("\nPrinting integer elements after sorting: ");

for(y = 0;y < x;y++)
System.out.print(array[y] + " ");
System.out.println();
}
}```

Output:

Sharing is healthy !!