• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

scjp

 
Vinod kashid
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i have problem with following code
String[] arr = {"java", "champ", "you"};
System.out.print(Arrays.binarySearch(arr, "java"));
System.out.print(Arrays.binarySearch(arr, "You"));

please explain output of above code.
 
Henry Wong
author
Marshal
Pie
Posts: 21427
84
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Vinod kashid wrote:i have problem with following code
String[] arr = {"java", "champ", "you"};
System.out.print(Arrays.binarySearch(arr, "java"));
System.out.print(Arrays.binarySearch(arr, "You"));

please explain output of above code.


Since the binarySearch() method requires that the array be sorted -- doing a search on an unsorted array, may or may not work.... so, are you saying that it works in some cases, and doesn't in others?

Henry
 
Vinod kashid
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Henry Wong wrote:
Vinod kashid wrote:i have problem with following code
String[] arr = {"java", "champ", "you"};
System.out.print(Arrays.binarySearch(arr, "java"));
System.out.print(Arrays.binarySearch(arr, "You"));

please explain output of above code.


Since the binarySearch() method requires that the array be sorted -- doing a search on an unsorted array, may or may not work.... so, are you saying that it works in some cases, and doesn't in others?

Henry


when i run this code i got output as -3 -1.
but when String[] arr = {"you", "champ", "java"}; output is 2 -1.
here arr[] is also unsorted .
 
Henry Wong
author
Marshal
Pie
Posts: 21427
84
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Vinod kashid wrote:
when i run this code i got output as -3 -1.
but when String[] arr = {"you", "champ", "java"}; output is 2 -1.
here arr[] is also unsorted .



With the array unsorted, it is *broken*. It may or it may not work. And as mentioned in the previous post, you can find examples that work, and you can find examples that won't work.

Henry
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic