Thanks Doug. Here\'s the fix:
void swap(int& a, int& b) {
if (&a == &b) // added this check to ensure the same address is not passed in
In addition to the existing answers, I'll just add that if you're going to do a test before swapping then you might as well change:
if (&a == &b) // added this check to ensure the same address is not passed in
return;
to:
if (a == b) // check that values are different
return;
This will handle the case where &a == &b
and also the case where a == b
, which may save some unnecessary swapping.