void swap(int &x, int &y) { x ^= y ^= x;
}
- or -
void swap(int &x, int &y) {
int t = x;
x = y;
y = t;
}
void swap(int& a, int& b ) { a^=b^=a^=b; }
// Note: ^ is the XOR operator a = a ^ b b = b ^ a a = a ^ b
To swap two variables without using a third variable, use exclusive or manipulation... a ^= b; b ^= a; a ^= b;
void swap (int &pa, int &pb) { *pa ^= *pb; *pb ^= *pa; *pa ^= *pb; }
You can swap two integers without temporary storage by bitwise exclusive-or'ing them in a specific sequence...a ^= b;b ^= a;a ^= b;
sum = a + b + c;
Ellipses (...) used to emulate indentation... swap(int *a, int *b) { ... int temp; ... temp = *a; ... *a = *b; ... *b = temp; }
You can't. While a string is a character array, an array is not necessarily a string. Treating arrays as if they were strings simply to swap them is madness. The correct way to physically swap arrays A and B is to copy A to a new array, C, then copy B to A, then C to B. If the arrays are the same size this is not a problem. If they are different sizes, you can only swap them if they are dynamic (not static). This means you must reallocate them. To speed up the process, copy the smallest array to C, first. A much better approach would be to point at the two arrays and swap the pointers instead.
bubble_sort (int N, int *A) { int i; swap = 1; while (swap) { swap = 0; for (i=0; i<N-1; ++i) { if (A[i] > A[i+1]) { swap = 1; A[i] ^= A[i+1]; A[i+1] ^= A[i]; A[i] ^= A[i+1]; } } } }
//lets assume a = 10; b = 20; a = a^b; b = a^b; a = a^b;
int main() { int x = 40 + 2; }
You have to pass the address of the variables.void swap (int *pa, int *pb){...}