3 ms·
99.9% of the time swaps are done for a reason, usually when sorting or manipulating linked lists pointers, but - for example - comes into play also when you wan
by xanathar 5y ago
99.9% of the time swaps are done for a reason, usually when sorting or manipulating linked lists pointers, but - for example - comes into play also when you want to transpose a matrix in place, or other similar algorithms.
I guess you can make an argument that the best way to get an array sorted is to have the array already sorted, but that sounds as "the best way to calculate the length of the hypotenuse is to just measure the hypotenuse, and Pythagoras never realized it was a problem upstream".
- jacquesm 5y agoOf course swaps are done 'for a reason'. But this is an implementation detail for a swap, one where the xor trick is used to be able to swap 'in place' without using a third variable to perform the swap, and that screams 'register constraints'. To get into that situation is the mistake, not to get clever to use an xor swap to get you back out of it. In any other situation that realistically speaking would occur such constraints would not normally exist.
- sokoloff 5y agoIn a sorting algorithm, if the XOR swap (or any other trick) is faster, that seems a valid use case. The constraint being “this sort library should be correct first and as fast as possible second.”
- jacquesm 5y agoI've implemented lots of sorting algorithms and have never found the XOR trick useful or faster. The main use was on very register constrained 8 bit machines but I haven't programmed on anything like that in assembly for years. Still, it's a neat trick.