lundi 25 septembre 2017

Having problems understanding a sorting bug

I wrote a program that generates a couple of random numbers and sorts them with a simple algorithm. But in the sorting algorithm I have these two variants of swapping the numbers in my loop:

for (iterator i = intv.begin(); i < intv.end(); i++)
{
    for (iterator j = i + 1; j < intv.end(); j++)
    {
        if (max(*i, *j) == *i)
        {
            /* Problem
            uint temp = *i;
            intv.erase(i);
            intv.insert(i, *j);
            intv.erase(j);
            intv.insert(j, temp);
            */

            uint temp = *j;
            intv.erase(j);
            intv.insert(j, *i);
            intv.erase(i);
            intv.insert(i, temp);
        }
    }
}

Here's an output from the working program:

6;3;5;2;5;9;0;6;6;5;
0;2;3;5;5;5;6;6;6;9;

And here's one from the problematic program:

5;5;1;1;6;9;3;2;5;4;
4;4;4;4;4;4;4;4;4;9;

Can somebody please explain to me what's the difference between the swapping mechanisms?

Aucun commentaire:

Enregistrer un commentaire