Created
February 21, 2012 18:30
-
-
Save thomashw/1877997 to your computer and use it in GitHub Desktop.
Example of implementing quick sort.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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