Swap In Place

/**
 * Write a method to swap two integers 
 * without using any extra memory.
 */

/*
Reasoning:
- <----------a-------b----------->
- Then b - a = distance(a,b)
- from b subtracting dist we get to a.
- from a adding dist we get to b.
*/

void inplace_swap(int &a, int &b)
{
    a = b - a;
    b = b - a;
    a = b + a;
}

int main()
{
    int a = 2;
    int b = 44;

    inplace_swap(a, b);
    cout << a << " " << b << endl;

    a = 344;
    b = 23;

    inplace_swap(a, b);
    cout << a << " " << b << endl;

    a = -120;
    b = 32;

    inplace_swap(a, b);
    cout << a << " " << b << endl;

    a = 23;
    b = -399;

    inplace_swap(a, b);
    cout << a << " " << b << endl;
}

Last updated