c - Why is temporary storage needed in sorting array? -
the piece of code :
if(a[i] > a[j]){ temp = a[i]; a[i] = a[j]; a[j] = temp; }
why temp variable has used ? when try without temp :
if(a[i] > a[j]){ a[i] = a[j]; }
it wont work, before working when compare other variables
if don't have temp variable
temp = a[i]; a[i] = a[j]; a[j] = temp;
then lose value in a[i]
(previous assignment a[i] = a[j]
.
there way swap values without having using temporal value. solution here.
in c this:
int x = 10, y = 5; // code swap 'x' (1010) , 'y' (0101) x = x ^ y; // x becomes 15 (1111) y = x ^ y; // y becomes 10 (1010) x = x ^ y; // x becomes 5 (0101)
using xor operator. code here, go link find entire explanation , possible drawbacks of using solution.
Comments
Post a Comment