Quicksort is a fast sorting algorithm, see the implementation in Java.

Configuration
Java Compilation:
Java Runtime:
JDK 11.0.12
JRE HotSpot 11.0.12
import java.util.Random; public class MainClass { final static int TOTAL = 50; public static void main(String[] args) { int[] elements = new int[TOTAL]; Random random = new Random(); for (int i = 0; i < TOTAL; i++) { elements[i] = random.nextInt(TOTAL); } for (int i = 0; i < TOTAL; i++) { System.out.print(elements[i] + " "); } System.out.println("started"); System.out.println(); quickSort(elements, 0, TOTAL - 1); System.out.println("Done: "); for (int i = 0; i < TOTAL; i++) { System.out.print(elements[i] + " "); } } private static void quickSort(int[] elements, int from, int to) { // if just 2 elements to sort, simply compare them and return. if even less than 2 elements to sort, simply return if (to - from <= 1) { if (to - from == 1) { if (elements[from] > elements[to]) { int temp = elements[from]; elements[from] = elements[to]; elements[to] = temp; } } return; } int leftCount = 0; int rightCount = 0; int pivotal = (from + to) / 2; // use the middle position to get the pivotal int[] pivotallyCompared = new int[elements.length]; for (int i = from; i <= to; i ++) { if (i != pivotal) { if (elements[i] > elements[pivotal]) { pivotallyCompared[to - rightCount++] = elements[i]; } else { pivotallyCompared[from + leftCount++] = elements[i]; } } } pivotallyCompared[from + leftCount] = elements[pivotal]; for (int i = from; i <= to; i++) { elements[i] = pivotallyCompared[i]; } quickSort(elements, from, from + leftCount - 1); quickSort(elements, from + leftCount + 1, to); } }
Some note about the code:
  • The input is an unsorted int array, with the values assigned randomly
  • The idea of quicksort is divide and conquer. First it will get the pivotal, in the example here it uses the middle position element
  • After mergesort each of the group, the 2 group each will be sorted. Then merge the 2 sorted group back into a sorted int array
  • Then looping through the array, whichever element has the value larger than the pivotal value will be put on the "Right" group, whichever less than the pivotal value will be on the "left" group
  • So the array will be re-arranged as "left group", "pivotal element", "right group". Then just use recursion to quicksort "left group" and "right group" until 2 or less elements are left
  • If just 2 elements to sort, simply compare them and return. if even less than 2 elements to sort, simply return
Sample output:
started:
44 29 7 30 30 35 16 11 23 34 48 14 7 42 18 26 12 24 15 25 2 49 34 2 21 29 41 37 20 17 29 8 49 12 5 37 32 23 19 13 32 44 48 10 15 35 0 47 14 33
Done:
0 2 2 5 7 7 8 10 11 12 12 13 14 14 15 15 16 17 18 19 20 21 23 23 24 25 26 29 29 29 30 30 32 32 33 34 34 35 35 37 37 41 42 44 44 47 48 48 49 49