I have to implement an iterative quicksort in java for homework. i've search a lot about it but i couldn't find a website with a clear explanation about how to implement an iterative quicksort.
i have found this code in java, and it sorts very well, but i can't tell how does it work, i know how the recursive quicksort works though.
i've commented the code with my questions
public static void iterativeQsort(int[] arr) {
Stack<Integer> stack = new Stack<Integer>();
stack.push(0);
stack.push(arr.length);
while (!stack.isEmpty()) {
int end = stack.pop();
int start = stack.pop();
if (end - start < 2) continue;
int p = start + ((end-start)/2);
p = partition(arr,p,start,end);
stack.push(p+1);
stack.push(end);
stack.push(start);
stack.push(p);
}
}
private static int partition(int[] arr, int p, int start, int end) {
int l = start;
int h = end - 2; //what is h and l variables for and why h has to be end -2?
int piv = arr[p];
swap(arr,p,end-1);
while (l < h) {
if (arr[l] < piv) {
l++;
} else if (arr[h] >= piv) {
h--;
} else {
swap(arr,l,h);
}
}
int idx = h; // what is idx exactly?
if (arr[h] < piv) idx++;
swap(arr,end-1,idx);
return idx; //why return idx.
}
private static void swap(int[] arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
i'm mostly confused by the partition method, i don't know what it does.
if someone could explain me the main steps to make an iterative quicksort i'll be very happy.
Thanks for your help.