I try to implement quicksort algorithm for int[]
. I coded the partition step correctly but then I wanted to call partition step method recursively to get the array sorted, unfortunately I pass wrong indexes to the recursive call and I get StackOverflow exception.
I based it on: https://www.youtube.com/watch?v=y_G9BkAm6B8
public class Quicksort {
public static void partition(int[] t, int i, int j) {
int start = i, end = j;
int pivot = t[(i + j) / 2]; // select the pivot as the middle value
System.out.println("pivot: " + pivot);
int temp;
while (i < j) {
while (t[i] < pivot) { // looking for value greater or equal to the
// pivot
i++;
}
while (t[j] > pivot) { // looking for value lower or equal to the
// pivot
j--;
}
System.out.println("i = " + i + " j = " + j + " swaps " + t[i] + " with " + t[j]);
temp = t[i]; // swap
t[i] = t[j];
t[j] = temp;
i++; // move to the next element
j--; // move to the prev element
display(t);
}
// I CALL THEM WRONG
partition(t, start, j); // partition for the left part of the array
partition(t, i, end); // partiion for the right part of the array
}
public static void display(int[] t) {
for (int el : t)
System.out.print(el + " ");
System.out.println();
}
public static void main(String[] args) {
int[] t = { 6, 4, 1, 32, 5, 7, 8, 6, 9, 1 };
display(t);
partition(t, 0, t.length - 1);
}
}