import java.util.Random;


public class Quicker {
	
	public static final int SIZE = 4;
	
	// This sorts the elements of A between index first and index last
	// using temp as temporary storage for the merger.
	private static <E extends Comparable<? super E>> void QuickSort(E[] A, int first, int last) {
		if (first < last) {
			int mid = (first+last)/2;
			E pivot = A[mid];
			swap(A, mid, last);
			int i = first; 
			int j = last;
			while ( i < j) {
				while (A[i].compareTo(pivot) < 0)
					i += 1;
				while (i < j && pivot.compareTo(A[j]) <= 0)
					j -= 1;
				if (i < j) 
					swap(A, i, j);
			}
			swap(A, last, i);
			QuickSort(A, first, i-1);
			QuickSort(A, i+1, last);
		}
		
	}
	

public static <E extends Comparable<? super E>>void QuickSort(E[] array ) {
		QuickSort(array, 0, array.length-1);
	}
	
public static void swap(Object[] A, int i, int j) {
	Object temp = A[i];
	A[i] = A[j];
	A[j] = temp;
}

	static void build(Object[] a) {
		Random rand = new Random();
		
		for (int i = 0; i < a.length; i++)
			a[i] = rand.nextInt(10*SIZE);
	}

	static void Print( String text, Object[] a) {
		if (a.length <= 10) {
			System.out.printf( "%s: ", text);
			for(int i = 0; i < a.length; i++ ) 
				System.out.printf( "%d   ", a[i]);
			System.out.println();
		}
		else {
			System.out.println( text );
			for (int i = 0; i < a.length; i++) 
				System.out.println( String.format( "   %d", a[i]) );
		}
	}
	
	public static void main(String[] args) {
		Integer[] data = new Integer[SIZE];
		build( data );
		Print("Original data", data);
		QuickSort(data);
		Print("Sorted data", data);
	}
}
