import java.util.Arrays;
import java.util.Scanner;
public class ElementSearch {
public static void main(String[] args) {
try{
Scanner scanner = new Scanner(System.in);
int arraySize = scanner.nextInt();
Integer array[]=new Integer[arraySize];
int count = 0;
while (count < arraySize) {
array[count]=scanner.nextInt();
count++;
}
System.out.println(Arrays.binarySearch(array, scanner.nextInt()));
}catch(Exception e){
System.out.println(e);
}
}
}
5
Your code not satisfied the condition actually if array element not found print -1 .But in your code it´s print -2 .Please check once your code.
Sample input i have taken (20 is not in array element) below .Check the same values from your end and let me know if your condition is satisfied or not:
6
12
61
50
25
65
12
20
-2
Yes, you are right. I just read about this method it returns (-(insertion point) - 1) if element not found, The insertion point is defined as the point at which the key would be inserted into the array and one more thing it should be sorted. so better yo use like this:
System.out.println(Arrays.asList(array).indexOf(scanner.nextInt()));
So, you have used the same concpet that i have used in the program right!!!.array convert to Arraylist and indexOf method for serach element.