java - Binary searching for string arrays -
how sort array of string binary search. below recieve minus number index instead of correct index. please help? if word not in array -1 should returned.
public static int binary (string [] theword, string a) { int index = -1; arrays.sort(theword); arrays.tostring(theword); index = arrays.binarysearch(theword, a); return index; }
it works, see below
public static void main(string... args) { string words[] = { "abc3", "abc2", "abc1", "abc4" }; arrays.sort(words); system.out.println(arrays.tostring(words)); { string word = "abc3"; int index = arrays.binarysearch(words, word); index = index >= 0 ? index : -1; system.out.println(word + " = " + index); } { string word = "abc11"; int index = arrays.binarysearch(words, word); index = index >= 0 ? index : -1; system.out.println(word + " = " + index); } }
output
[abc1, abc2, abc3, abc4] abc3 = 2 abc11 = -1
you return index sorted array while need index original array.
Comments
Post a Comment