Maestro
Maestro

Reputation: 2572

Why using Xor operator to swap objects in selection sort doesn't't work?

I have this simple example that implements select sort algorithm:

int main(){

    vector<int> vi{ 5, 7, 23, 7, 23, 5, 
    77, 10, 57, 23,  2  };
    int min = 0;
    for(int i = 0; i < vi.size() - 1; ++i){
        min = i;
        for(int j = i + 1; j < vi.size(); ++j){
            if(vi[j] < vi[min]){
                min = j;
            }
        }
            vi[i] ^= vi[min];
            vi[min] ^= vi[i];
            vi[i] ^= vi[min];
     //int tmp = vi[i];
            //vi[i] = vi[min];
            //vi[min] = tmp;
    }

    for(auto i : vi)
        cout << i << ", ";
    cout << endl;

    cout << endl;
}

The problem is when using a temporary object to swap values works fine but using Xor operator I get wrong results!!

Here is the output of using Xor operator:

2, 5, 5, 0, 7, 10, 23, 23, 23, 57, 77, 

And here is the correct result using a temporary object:

2, 5, 5, 7, 7, 10, 23, 23, 23, 57, 77, 

Upvotes: 1

Views: 260

Answers (1)

Jeffrey
Jeffrey

Reputation: 11430

when i == min you get:

        vi[i] ^= vi[i];
        vi[i] ^= vi[i];
        vi[i] ^= vi[i];

which is the same as

        vi[i] = 0;

just less readable, less efficient, and not as general as swap, which always work.

You should use

std::swap(vi[i], vi[min]);

Upvotes: 7

Related Questions