somehow the last element of my input does not get sorted with the list i am feeding to the quicksort method
for example
input : 5,7,3,2,7,8,9,0,3,1,2,3
result: 0 1 2 2 3 3 5 7 7 8 9 3
input: 5,4,2,12,9,4
result: 2 4 5 9 12 4
any ideas where i am going wrong?
public class QuickSort2 {
private static void quickSort(int[] list) {
quickSort(list, 0, list.length - 1);
}
private static void quickSort(int[] list, int p, int q) {
if (p < q) {
int pivotIndex = partition(list, p, q);
quickSort(list, p, pivotIndex - 1);
quickSort(list, pivotIndex + 1, q);
}
}
private static int partition(int[] list, int p, int q) {
int x = list[p];
int i = p;
int temp, temp2;
for (int j = p + 1; j < list.length - 1; j++) {
if (list[j] < x) {
i = i + 1;
// exchange list[i] with list[j]
temp = list[i];
list[i] = list[j];
list[j] = temp;
}
}
// exchange list[p] with list[i]
temp2 = list[p];
list[p] = list[i];
list[i] = temp2;
return i;
}
}
edit
public class QuickSort2 {
private static void quickSort(int[] list) {
quickSort(list, 0, list.length - 1);
}
private static void quickSort(int[] list, int p, int q) {
if (p < q) {
int pivotIndex = partition(list, p, q);
quickSort(list, p, pivotIndex - 1);
quickSort(list, pivotIndex + 1, q);
}
}
private static int partition(int[] list, int p, int q) {
int x = list[p];
int i = p;
int temp, temp2;
for (int j = p + 1; j <= q; j++) {
if (list[j] < x) {
i = i + 1;
// exchange list[i] with list[j]
temp = list[i];
list[i] = list[j];
list[j] = temp;
}
}
// exchange list[p] with list[i]
temp2 = list[p];
list[p] = list[i];
list[i] = temp2;
return i;
}
}