Saturday, May 8, 2010

Seraching in Arrays in JAVA

We can search in a array for a value using the method binarySearch of Arrays class.
The search result will give correct output if the array is sorted.
If the array is not sorted the result is unpredictable.
Note: For predictable result array must be sorted before searching an element.

The following code explains this behavior:


Integer[] intArr={2,5,3,4,1};
for(Integer s: intArr)
System.out.print(s+",");

System.out.print(System.lineSeparator());
System.out.print("Searching 5:"+Arrays.binarySearch(intArr,5)); // Will return -6 which is incorrect
System.out.print(System.lineSeparator());
System.out.print("Searching 2:"+Arrays.binarySearch(intArr,2)); // will return correct result 0, but not for every search

Arrays.sort(intArr); //Sorting the Array
System.out.print(System.lineSeparator());
for(Integer s: intArr)
System.out.print(s+",");
System.out.println(System.lineSeparator()+Arrays.binarySearch(intArr,2)); // Always gives the correct result


No comments:

Post a Comment

About Me