Skip to content

Instantly share code, notes, and snippets.

@noroutine
Created May 3, 2016 16:00
Show Gist options
  • Save noroutine/c9f6fcb9b2e1090364e22b8cb391f21e to your computer and use it in GitHub Desktop.
Save noroutine/c9f6fcb9b2e1090364e22b8cb391f21e to your computer and use it in GitHub Desktop.
public class Quicksort
{
public static void main(String[] args) {
int a[] = new int[] {
10, 4, 4, 8, 0, 8, 9, 7, 3, 7, 6
};
Quicksort.sort(a);
for (int e: a) {
System.out.print(e);
System.out.print(" ");
};
System.out.println();
}
public static void sort(int[] a)
{
qsort(a, 0, a.length - 1);
}
private static void qsort(int[] a, int start, int stop)
{
if (start < stop) {
int pivot = pos(a, start, stop);
qsort(a, start, pivot);
qsort(a, pivot + 1, stop);
}
}
private static int pos(int[] a, int start, int stop)
{
int i = start;
int j = stop;
int pivot = i;
while (i < j)
{
if (a[i] > a[j])
{
int aux = a[i];
a[i] = a[j];
a[j] = aux;
pivot = pivot == i ? j : i;
}
if (pivot == i)
{
j--;
}
else
{
i++;
}
}
return pivot;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment