java - why getting wrong answer when using Collections.binarySearch() -


public class binarysearchcollections {   public static void search(list<string> list) {     list.clear();     list.add("b");     list.add("a");     list.add("c");     system.out.println(collections.binarysearch(list, "b"));     system.out.println(list);   }   public static void main(string[] args) {     list<string> lis = new arraylist<string>();     binarysearchcollections bs = new binarysearchcollections();     bs.search(lis);   } } 

here getting ans -3 (as telling me @ location going added) have b in list.

your original list isn't sorted, binary search going give nonsense answer.

imagine steps takes:

"is b > a? yes, higher."

"is b > c? no, can't go lower, insert @ index 2 (aka return -3.)"

if want binary search work, give list on can take meaningful steps, , give correct answer.


Comments

Popular posts from this blog

linux - Does gcc have any options to add version info in ELF binary file? -

android - send complex objects as post php java -

charts - What graph/dashboard product is facebook using in Dashboard: PUE & WUE -