Thursday, January 22, 2009

Quicksort implementation in Java

Quicksort is a well known sorting algorithm. You can find more information about it here. Following is an implementation of Quicksort in Java with generics.

public class QuickSort {

/**
* Quicksort using Java generics
* @param a an array of Comparable items.
*/
public static <T extends Comparable<T>>
void doQuickSort(T[] a) {
if (a == null) {
throw new
IllegalArgumentException("Input Array cannot be null");
}
int length = a.length;
if (length == 1) return;
doQuickSort(a, 0, length-1);
}

/**
* Actual quicksort implementation using
* median of 3 partitioning.
* @param a an array of Comparable items.
* @param left the left index of the subarray.
* @param right the right index of the subarray.
*/
private static <T extends Comparable<T>> void
doQuickSort(T[] a, int left, int right) {

//Base case
if (left >= right) return;

//Choose the pivot using median of 3 partitioning
//using the following 2 steps
//First step: find the center
int center = (left+right)/2;
//Second step: sort left, center and right
if (a[left].compareTo(a[center]) > 0) {
swap(a, left, center);
}
if (a[left].compareTo(a[right]) > 0) {
swap(a, left, right);
}
if (a[center].compareTo(a[right]) > 0) {
swap(a, center, right);
}
//Third Step:
//Got the pivot and it is at the center.
//Move it to the end of the array.
swap(a,center,right-1);
int pivot = right-1;

//Partition the array
int i = left,j = right - 2;
if (j >= 0) {
for(;;) {
while (a[i].compareTo(a[pivot])< 0) {
i++;
}
while(a[j].compareTo(a[pivot]) > 0) {
j--;
}
if (i >= j) break;
swap(a,i,j);
}
}
//Put the pivot at ith position of the array
swap(a,i,right-1);
//Now all the elements to the right of i are less than
//it and all the elements to the left of i are greater
//than it. So partition the array and
//recursively call quicksort on the left and right partition
doQuickSort(a, left, i-1);
doQuickSort(a, i+1, right);

}

/**
* Internal method to swap to elements in an array.
* @param a an array of objects.
* @param left the index of the first object.
* @param right the index of the second object.
*/
private static <T extends Comparable<T>>
void swap(T[] a, int left, int right) {
T temp = a[left];
a[left] = a[right];
a[right] = temp;
}

//Test it
public static void main(String[] args) {
Integer[] input = {5,14,16,2,17,1,8,6,0,9};
doQuickSort(input);
printArray(input);
String[] str = new String[]{"adc","abc", "acd", "aaa"};
doQuickSort(str);
printArray(str);
}

/**
* Internal method to print the elements in an array.
* @param a an array of objects.
*/
private static <T extends Comparable<T>>
void printArray(T[] a) {
for (T elem: a) {
System.out.println(elem);
}
}

}



Output on running the above program:
0
1
2
5
6
8
9
14
16
17
aaa
abc
acd
adc

1 comment: