Below is an example of the Quicksort algorithm in Java. See the Quicksort page for more information and implementations.
public class QuickSort { public static void main(String[] args) { int[] array = {12, 11, 15, 10, 9, 1, 2, 3, 13, 14, 4, 5, 6, 7, 8}; QuickSort sorter = new QuickSort(); sorter.quickSort(array, 0, array.length - 1); System.out.println(java.util.Arrays.toString(array)); } private void quickSort(int[] array, int startIndex, int endIndex) { // verify that the start and end index have not overlapped if (startIndex < endIndex) { // calculate the pivotIndex int pivotIndex = partition(array, startIndex, endIndex); // sort the left sub-array quickSort(array, startIndex, pivotIndex); // sort the right sub-array quickSort(array, pivotIndex + 1, endIndex); } } private int partition(int[] array, int startIndex, int endIndex) { int pivotIndex = (startIndex + endIndex) / 2; int pivotValue = array[pivotIndex]; startIndex--; endIndex++; while (true) { // start at the FIRST index of the sub-array and increment // FORWARD until we find a value that is > pivotValue do startIndex++; while (array[startIndex] < pivotValue); // start at the LAST index of the sub-array and increment // BACKWARD until we find a value that is < pivotValue do endIndex--; while (array[endIndex] > pivotValue); if (startIndex >= endIndex) return endIndex; // swap values at the startIndex and endIndex int temp = array[startIndex]; array[startIndex] = array[endIndex]; array[endIndex] = temp; } } }