It works fine for 10 to 50 random item lists, but when I hit 1000 it gets unstable, and sometimes stack overflow occurs, 1000 is even worse. code as followed :
public class InPlaceQuickSort {
int array[] = {};
public InPlaceQuickSort(int[] consArray) {
array = consArray;
}
public void qsort(int left, int right) {
int oldRight = right;
int oldLeft = left;
int pivot = left;
while (array[left] <= array[pivot]) { // increase left pointer until bigger than pivot
left = left + 1;
if (left >= array.length) {
break;
}
}
while (array[right] > array[pivot]) { // decrease right pointer until smaller than pivot
right = right - 1;
if (right == 0) {
break;
}
}
if (right <= left) {
swap(pivot,right); // right change to pivot
if ((oldRight - right) >= 2) { // here we do right chunk if there are
qsort(right+1, oldRight);
}
if ((right - oldLeft) > 2) { // here we do left chunk if there are
qsort(0, right - 1);
}
} else {
swap(left, right); // swap both anomoly
qsort(pivot, oldRight);
}
}
private void swap(int n1, int n2) {
int tmp = array[n1];
array[n1] = array[n2];
array[n2] = tmp;
}
}