Skip to content

Instantly share code, notes, and snippets.

@vaskoz
Last active August 29, 2015 14:22
Show Gist options
  • Save vaskoz/13655cfb8f236575f0d9 to your computer and use it in GitHub Desktop.
Save vaskoz/13655cfb8f236575f0d9 to your computer and use it in GitHub Desktop.
import java.util.Stack;
public class StackedQuicksort {
public static void sort(Comparable<?>[] data, int left, int right) {
Stack<Integer> stack = new Stack<>();
stack.push(left);
stack.push(right);
while (!stack.empty()) {
right = stack.pop();
left = stack.pop();
if (left >= right) continue;
int pi = partition(data, left, right);
stack.push(left);
stack.push(pi - 1);
stack.push(pi + 1);
stack.push(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