lolz, with all the cout's you placed it was a bit confusing for me. Anyways, the reason it is being called twice is because it's a recursive function so it calls itself, and after the second call to itself is done it returns back to where it stopped in your first call and starts executing from there.
so basically it's like this
main calls quicksort
quicksort calls qs
qs finds a call to itself and jumps to executing a second qs.
second qs finishes executing and goes back to the first qs call and resumes executing the
remaining statements in the first qs.
it sees the following code block and executes it as well, changing the values of your variables.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
|
do {
while((items[i] < x) && (i < right)) {
i++;
cout << "in the while loop i = " << i << "\n";
}
while((x < items[j]) && (j > left)) {
j--;
cout << "in the while loop j = " << j << "\n";
}
if(i <= j) {
y = items [i];
items[i] = items[j];
items[j] = y;
i++; j--;
cout << "at the end of nested if i = " << i << " and j = " << j << "\n";
}
} while(i <= j);
| |
then it checks your values in the if statement , i = 2 and right = 4 now though so it becomes true. and executes the statements inside of it.
then the first qs finishes and returns to quicksort.
quicksort finishes and returns to main
main reaches it's end and stops executing.
It probably makes more than 2 calls to itself though because it's sorting out the string. But logically that's how it's happening. Hopefully that explains it well enough. :P