Skip to content

Instantly share code, notes, and snippets.

@thomashw
Created February 21, 2012 18:30
Show Gist options
  • Save thomashw/1877997 to your computer and use it in GitHub Desktop.
Save thomashw/1877997 to your computer and use it in GitHub Desktop.
Example of implementing quick sort.
import java.util.Arrays;
public class QuickSort
{
public int[] a;
public QuickSort()
{
a = new int[] { 0, 6, 41, 54, 57, 874, 243, 324, 1, 23, 4, 69, 7, 104 };
}
public void quicksort(int lo, int hi)
{
int m = (lo+hi)/2;
int pivot = a[m];
int i = lo;
int j = hi;
int temp;
System.out.println( "\nPivot: " + pivot );
System.out.println( Arrays.toString( a ));
if( hi - lo < 1 )
return;
while( j > i )
{
while( a[i] < pivot && i < j )
i++;
while( a[j] > pivot && i < j )
j--;
if( i < j ) {
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
if( j < i ) {
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
quicksort( lo, i );
quicksort( i == lo ? i + 1 : i, hi );
}
public static void main( String[] args )
{
QuickSort qs = new QuickSort();
qs.quicksort( 0, qs.a.length - 1 );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment