Skip to content

Instantly share code, notes, and snippets.

@rptynan
Created January 26, 2015 22:44
Show Gist options
  • Save rptynan/28b4bcd55b3bb3a6b268 to your computer and use it in GitHub Desktop.
Save rptynan/28b4bcd55b3bb3a6b268 to your computer and use it in GitHub Desktop.
Quicksort Java
// Quick sort, worst case, O(n^2), average, O(nlogn), unstable
package sorting;
public class Quick extends Sorter {
java.util.Random rand;
private void recurse(int[] a, int L, int R) {
if( (R-L) <= 1 ) return;
int p = choosePivot(L, R);
swap(p, R-1, a);
p = R-1;
int l = L, r = R-1;
while( l < r ){
while( l < r && lesseq(a[l], a[p]) ) ++l;
while( l < r && less(a[p], a[r-1]) ) --r;
if( l < r ) swap(l, r-1, a);
}
swap(r, p, a);
recurse(a, L, l);
recurse(a, l+1, R);
}
private int choosePivot(int l, int r) {
// Random int in range [l,r]
return rand.nextInt(r-l) + l ;
}
public void sort(int[] a) throws RuntimeException {
rand = new java.util.Random(1);
recurse(a, 0, a.length);
return;
}
public Quick(String name) {
super(name);
}
}// Quick sort, worst case, O(n^2), average, O(nlogn), unstable
package sorting;
public class Quick extends Sorter {
java.util.Random rand;
private void recurse(int[] a, int L, int R) {
if( (R-L) <= 1 ) return;
int p = choosePivot(L, R);
swap(p, R-1, a);
p = R-1;
int l = L, r = R-1;
while( l < r ){
while( l < r && lesseq(a[l], a[p]) ) ++l;
while( l < r && less(a[p], a[r-1]) ) --r;
if( l < r ) swap(l, r-1, a);
}
swap(r, p, a);
recurse(a, L, l);
recurse(a, l+1, R);
}
private int choosePivot(int l, int r) {
// Random int in range [l,r]
return rand.nextInt(r-l) + l ;
}
public void sort(int[] a) throws RuntimeException {
rand = new java.util.Random(1);
recurse(a, 0, a.length);
return;
}
public Quick(String name) {
super(name);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment