+ 5

Performance of swap function

in c,cpp we of many different ways to swap two values all of them are listed here. https://geekfactorial.blogspot.com/2016/08/the-many-different-ways-of-swapping-two-numbers.html?m=1 Can any one tell best performance wise best method from all methods mentioned in above link? one more that is not listed on above link, void swap(int* array,int i,int j) { int temp = array[i]; array[i] = array[j]; array[j] = temp; } John Wells MAX Ipang kajal mohite Ketan Lalcheta SagaTheGreat 💯

3rd Jul 2018, 1:57 AM
$¢𝐎₹𝔭!𝐨𝓝
$¢𝐎₹𝔭!𝐨𝓝 - avatar
4 Respuestas
+ 9
we cannot add,multiply,divide two pointers. Two pointers can be compared like two integer numbers.All relational and logical operations can be used with pointers. hence for above swap using xor,and it's efficient also.
3rd Jul 2018, 3:12 AM
kajal mohite
kajal mohite - avatar
+ 8
You don't want to use math operators because they take longer to execute. The xor is the fastest operator. However, the three assignments using a temporary is the fastest method. The compiler will optimize and likely not even use the temporary.
3rd Jul 2018, 2:25 AM
John Wells
John Wells - avatar
+ 3
don't go with third variable atleast... it is not efficient at all compared to other methods...
3rd Jul 2018, 2:25 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
+ 2
check the code from below link.. it is not working on SL. but I am getting less time to swap if we swap using operations compared to swap using third variable.. https://code.sololearn.com/cRjPOzcZ12GN/?ref=app
3rd Jul 2018, 4:14 AM
Ketan Lalcheta
Ketan Lalcheta - avatar