Created
June 7, 2015 00:35
-
-
Save vaskoz/bd7a9856cb7ffd77fff2 to your computer and use it in GitHub Desktop.
Implementation of Quicksort in Algorithms in a Nutshell
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.Comparator; | |
public class Quicksort { | |
public static void sort(Comparable<?>[] data, int left, int right) { | |
if (left < right) { | |
int pi = partition(data, left, right); | |
sort(data, left, pi-1); | |
sort(data, pi+1, right); | |
} | |
} | |
private static int partition(Comparable<?>[] data, int left, int right) { | |
int p = right; | |
int store = left; | |
Comparable val2 = data[p]; | |
for (int i = left; i < right; i++) { | |
Comparable val1 = data[i]; | |
if (val1.compareTo(val2) <= 0) { | |
swap(data, i, store); | |
store++; | |
} | |
} | |
swap(data, store, right); | |
return store; | |
} | |
private static void swap(Comparable<?>[] data, int x, int y) { | |
Comparable<?> temp = data[x]; | |
data[x] = data[y]; | |
data[y] = temp; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment