I am working on a projekt (for school) and one of the requirements is to sort an array. So I decided to use the quicksort. (I chose it because it is an algorithm that I don't know by now) I managed to understand how it works and I also found an option of its implementation in c++.
void quicksort(size_t v[], size_t start_pos, size_t end_pos)
{
size_t i, j, di, dj;
if (start_pos < end_pos)
{
i = start_pos, j = end_pos;
di = 0, dj = 1;
do
{
while (i < j && (v[j] > v[i] || v[j] == v[i])) i += di, j -= dj;
if (i < j)
std::swap(v[i], v[j]), di = (di + 1) % 2, dj = (dj + 1) % 2;
} while (i < j);
if (i - start_pos > 1)
sort(v, start_pos, i - 1);
if (end_pos - i > 1)
sort(v, i + 1, end_pos);
}
}
What I don't understand is... why in the last 2 if statements is used ">1"? I hope someone can clarify this for me. Thank you! :)
sort?size_t(!?), abuse of the comma operator, delta variablesdi,djwhich have values 0 or 1 and make the logic more complex, the code to flip the deltasdi = (di+1)%2(when a xor or a!suffices), the weird condition(v[j] > v[i] || v[j] == v[i])(why not>=?).