I have a code for quicksort in C++ that works perfectly for an array of non-unique elements. I'm sure that a lot of people here knows it, but, who does understand it? Let me explain myself better. This is the code:
void quicksort(int a[], int first, int last){
int i,j;
int pivot;
if((last -first + 1) <= 1) return;
pivot = a[(first+last) / 2];
i = first;
j = last;
while(i <= j){
while(a[i] < pivot) i++;
while(a[j] > pivot) j--;
if(i <= j){
//SWAP
int temp = a[i];
a[i] = a[j];
a[j] = temp;
i++;
j--;
}
}
quicksort(a, first, j);
quicksort(a,i, last);
}
So, i understand everything but the if on the swap. Can anyone tell me, mathematically, what is the exact case or set of cases where i > j after the two inner whiles? I know specific cases for it, but what is the mathematical (or exact) property of them for happening?
Sorry for the crappy english, and thanks.
PD: Ignore in this case optimizations, or choosing the pivot and all that stuff, please.