Quick Sort Java Implementation Code

import java.util.Arrays;

class QuickSort {
	public static void main(String[] args) {
		int[] inputArray = new int[] { 89,5 ,27, 18, 9, 3, 27, 54, 21, 108 };
		QuickSort uc = new QuickSort();
		uc.quickSort(inputArray, 0, inputArray.length - 1);
		System.out.println(Arrays.toString(inputArray));
	}

	private void quickSort(int[] array, int start, int end) {
		if (start < end) {
			int p = partition(array, start, end);
			quickSort(array, start, p - 1);
			quickSort(array, p + 1, end);
		}
	}

	private int partition(int[] array, int start, int end) {
		int pivot = array[end];
		int i = start - 1;
		int j = start;
		while(j <= end-1) {
			if (array[j] <= pivot) {
					++i;
					int iVal = array[i];
					int jVal = array[j];
					array[j] = iVal;
					array[i] = jVal;
			} 
			j++;
		}
		int iVal = array[i+1];
		array[end] = iVal;
		array[i+1] = pivot;
		return i+1;
	}
}

Output:

[3, 5, 9, 18, 21, 27, 27, 54, 89, 108]

11 comments

Leave a Reply