M
M
Maxim Rybalkin2019-04-22 15:33:19
Java
Maxim Rybalkin, 2019-04-22 15:33:19

What would be the relationship between the System.arraycopy() and Arrays.binarySearch() methods in this usage?

Here is a brief visual interface of System.arraycopy()
KBdLavZv1Mg.jpg
And this is a translation of the official documentation about the work of Arrays.binarySearch():

If there is no object in the search, then the value (-(insert point) - 1) is returned.
The insertion point is defined as the point at which the key will be inserted into the array:
1) Index of the first element in the range is greater than the key
2) toIndex if all elements in the range are less than the specified key. Note that this guarantees that the return value will be >= 0 if and only if the key is found.

Question - will the returned int of the binarySearch() method be used in arraycopy() as a position in the final array (4th line of the picture)?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Alexandrov, 2019-04-22
@jamakasi666

The question is not entirely clear, it would be better for you to throw in the code what exactly causes the question in you.
And so on a note
- for binarySearch, the array must always be sorted, otherwise the behavior will be erroneous and unpredictable
- binarySearch will return the position of the desired element or -1 if it is not there (or if the array is not sorted)
Relatively speaking, you have the following picture and in principle everything is very clear here what and where.

int sourcePos = Arrays.binarySearch(source_arr,40);  //3
int destPos     = Arrays.binarySearch(dest_arr,65);     //5
int len =4;
System.arraycopy(source_arr, sourcePos, 
                              dest_arr,    destPos,     len);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question