I have an array x of n >= 4 elements, at indices 0..n-1. I want to swap the elements at indices j and k, where 0 <= k < j < n with the elements at indices 0 and 1 (it doesn't matter whether x[j] ends up at x[0] or x[1]). My question is whether there is an unconditional algorithm for doing so.
I've only been able to come up with:
if k==1
// Exchange j with 0
temp=x[j];
x[j]=x[0];
x[0]=temp;
else
// Exchange k with 0
temp=x[k];
x[k]=x[0];
x[0]=temp;
// Exchange j with 1
temp=x[j];
x[j]=x[1];
x[1]=temp;
Is there a way of doing this without an if-statement?
After the swapping, x[0] and x[1] must contain what was originally in x[j] and x[k] (in either order), and x[j] and x[k] must contain what was originally in x[0] and x[1] (in either order).
ifstatement or any other "conditional" code path?k=0andj=1you don't want to swap anything?if-block and use theelse-block in all cases. If you can't do that, then, can you add more information about the requirements that preclude that?