aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Collection Problem - binarySearch Problem Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Collection Problem - binarySearch Problem" Watch "Collection Problem - binarySearch Problem" New topic
Author

Collection Problem - binarySearch Problem

Aashu Mahajan
Ranch Hand

Joined: May 27, 2011
Posts: 113

Hello guys, Here the Que. is from javachamp.com.

output


I didn't understand why it prints the correct location for line-1 and line-3 but not for line-2.
'Integer[] arr' array is not sorted so how can it give the position for line1 and line3 correct???
Muneeswaran Balasubramanian
Ranch Hand

Joined: Mar 19, 2010
Posts: 138
Hi Aashu,

Here nothing is the correct answer.
If you wants the perform binary search,
Before that search you have to sort the datas.


Put the line

before line 1,

Then you will get the correct answer.

Happy Preparation...


Cheers Munees
My Blog
Aashu Mahajan
Ranch Hand

Joined: May 27, 2011
Posts: 113

Thanks Muneeswaran Balasubramanian ,

now i have understood that the correct position would only be when we sort array before searching the elements in array.
dennis deems
Ranch Hand

Joined: Mar 12, 2011
Posts: 808
From Arrays.binarySearch javadoc:

The array must be sorted (as by the sort(int[]) method) prior to making this call. If it is not sorted, the results are undefined.
Shanky Sohar
Ranch Hand

Joined: Mar 17, 2010
Posts: 1051

Line-2 prints anonymous result because there is no element at third location in the array.


SCJP6.0,My blog Ranchers from Delhi
Aashu Mahajan
Ranch Hand

Joined: May 27, 2011
Posts: 113

@Shanky Sohar

I think without sorting array, the result would be totally unpredictable even if we place any value in same array on 3rd position. What you say??
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Collection Problem - binarySearch Problem