Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Collection Problem - binarySearch Problem

 
Aashu Mahajan
Ranch Hand
Posts: 114
Eclipse IDE Java Oracle
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 138
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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...
 
Aashu Mahajan
Ranch Hand
Posts: 114
Eclipse IDE Java Oracle
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 808
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1051
Eclipse IDE Firefox Browser
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Line-2 prints anonymous result because there is no element at third location in the array.
 
Aashu Mahajan
Ranch Hand
Posts: 114
Eclipse IDE Java Oracle
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
@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
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic