Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Campbell Ritchie
  • Tim Cooke
  • Bear Bibeault
Sheriffs:
  • Paul Clapham
  • Junilu Lacar
  • Knute Snortum
Saloon Keepers:
  • Ron McLeod
  • Ganesh Patekar
  • Tim Moores
  • Pete Letkeman
  • Stephan van Hulst
Bartenders:
  • Carey Brown
  • Tim Holloway
  • Joe Ess

Binary Search doubt  RSS feed

 
Ranch Hand
Posts: 58
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Given a properly prepared String array containing five elements, which

range of results could a
proper invocation of Arrays.binarySearch() produce?
A. 0 through 4
B. 0 through 5
C. -1 through 4
D. -1 through 5
E. -5 through 4
F. -5 through 5
G. -6 through 4
H. -6 through 5

Answer:
3 G is correct. If a match is found, binarySearch()will return the
index of the element that was matched. If no match is found, binarySearch() will return a negative number that,if inverted and then decremented, gives you the insertion point (array index) at which the
value searched on should be inserted into the array to maintain a
proper sort.
A, B, C, D, E, F, and H are incorrect based on the above. (Objective
6.5)

Can any one please expalin me why only G

Source KB Book
 
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi friend.....
you must be knowing if it gets a match it returns the index......
therefore you must be understanding 0 to 4.......
for the ans of -6 to -1 is
that index returned for no match is
as (-(insertion point)-1)....we have insertion points as .....
0,1,2,3,4,5......
5 because we can insert it after the last element......
putting these in the formula you will have -1 to -6.....
 
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The API says a binary search returns the...

...index of the search key, if it is contained in the array; otherwise, (-(insertion point) - 1). The insertion point is defined as the point at which the key would be inserted into the array: the index of the first element greater than the key, or a.length if all elements in the array are less than the specified key.


So for a sorted array containing 5 elements...
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!