Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is more expensive operation swap or comparison in integer array in Java

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.

like image 460
Walt Avatar asked Jan 11 '15 12:01

Walt


People also ask

How many comparisons and swaps does insertion sort require to sort?

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.

Why use compare and swap?

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.

How does swap and compare work in Java?

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.


1 Answers

Swap should be more expensive because it includes:

  1. Reading data from memory to cache
  2. Reading data from cache to registers
  3. Writing data back to cache

Comparison should be less expensive because it includes:

  1. Reading data from memory to cache
  2. Reading data from cache to registers
  3. Executing single compare operations on two registers (which should be a little faster than writing two integers into a cache)

But modern processors are complex and different from each other, so the best way to get the right answer is to benchmark your code.

like image 78
Ivan Mushketyk Avatar answered Nov 03 '22 01:11

Ivan Mushketyk