Many examples on the web about Quicksort (in Java) are close to this:
private void quicksort(int low, int high) {
int i = low, j = high;
int pivot = numbers[low + (high-low)/2];
while (i <= j) {
while (numbers[i] < pivot) {
i++;
}
while (numbers[j] > pivot) {
j--;
}
if (i <= j) {
exchange(i, j);
i++;
j--;
}
}
if (low < j)
quicksort(low, j);
if (i < high)
quicksort(i, high);
}
The thing I'm puzzled about is why there are those equals checks:
1) while (i <= j)
instead of while (i < j)
2) if (i <= j)
instead of if (i < j)
Are there any edge cases where this equals is crucial? From my understanding if we would have if(i == j)
, then we would basically exchange the same value with the same value.
Anybody can solve that puzzle for me?