Which is more expensive operation swap or comparison in integer array in Java ? Or they can all be thought as same ?
Context: Sorting for an almost sorted array (I am not talking about k-sorted array where each element is displaced from the right position by at most k). Even if we use insertion sort, number of comparisons by the end will be same as they would have been for any array or for worst case. Isn't it ? It is just that swaps will be fewer. Please correct if I am wrong.
In the expected case, insertion sort requires 1/4(N2 - N) comparisons, and thus should require about 1/2 the comparisons needed by selection sort.
In computer science, compare-and-swap (CAS) is an atomic instruction used in multithreading to achieve synchronization. It compares the contents of a memory location with a given value and, only if they are the same, modifies the contents of that memory location to a new given value.
Compare and swap is a technique used when designing concurrent algorithms. The approach is to compare the actual value of the variable to the expected value of the variable and if the actual value matches the expected value, then swap the actual value of the variable for the new value passed in.
Swap should be more expensive because it includes:
Comparison should be less expensive because it includes:
But modern processors are complex and different from each other, so the best way to get the right answer is to benchmark your code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With