# Java quick sort algorithm example

## Quicksort sort

Quicksort is a divide and conquer algorithm. Quicksort first divides a large array into two smaller sub-arrays: the low elements and the high elements. Quicksort can then recursively sort the sub-arrays.

## Quicksort steps:

• Pick an element, called a pivot, from the array.
• Partitioning: reorder the array so that all elements with values less than the pivot come before the pivot, while all elements with values greater than the pivot come after it (equal values can go either way). After this partitioning, the pivot is in its final position. This is called the partition operation.
• Recursively apply the above steps to the sub-array of elements with smaller values and separately to the sub-array of elements with greater values.

The base case of the recursion is arrays of size zero or one, which are in order by definition, so they never need to be sorted.

## Example

```package com.codesjava;   public class Test { public static int[] insertionSort(int data[]) { int temp; for (int i = 1; i < data.length; i++) { for(int j = i ; j > 0 ; j--){ if(data[j] < data[j-1]){ temp = data[j]; data[j] = data[j-1]; data[j-1] = temp; } } } return data; }   private static void printNumbers(int[] data) { for (int i = 0; i < data.length; i++) { System.out.print(data[i]); if(i != data.length-1){ System.out.print(", "); } } System.out.println("\n"); }   public static void main(String args[]){ int[] data = {8, 2, 4, 9, 3, 6}; //Print array elements printNumbers(data); int[] sortedDate = insertionSort(data); //Print sorted array elements printNumbers(sortedDate); } }```

## Output

```8, 2, 4, 9, 3, 6   2, 3, 4, 6, 8, 9```
Please follow and like us:

Copyright © 2020 CodesJava