Last active
August 29, 2015 14:22
-
-
Save vaskoz/13655cfb8f236575f0d9 to your computer and use it in GitHub Desktop.
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.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