Big sister of swap(x,y) function

How do you think, if you would need to generalize swap(x,y) function - How it would look like ? We all know that in standard case swap() is just:

x,y = y,x;

But if swap could accept 3 elements or even more, up until n, - How it would act ? Or we can state problem in different way - Of what general algorithm swap() is specific case ?

I'll show pseudo-code of that general algorithm :

function (tuple) {
  for (i=0; i < n=size(tuple)-i-1; i++)
    swap(tuple[i], tuple[n]);

Can you guess this function name ? Indeed, it's a reverse algorithm ! So when tuple size downgrades to 2, then reverse algorithm becomes a simple swap operation. In effect we can say that

reverse((x,y)) ☰ swap


reverse((x,y, ..., n)) has n/2 swap() operations, so complexity is O(n).


Now we know that generalized swap() is simply a reverse() operation.

No Comments Yet