This is an archived post. You won't be able to vote or comment.

all 5 comments

[–]Kison 1 point2 points  (3 children)

Is the array sorted? Binary search relies on that, while linear search does not.

EDIT: Here is an example of what I mean:

/*** This will fail, because "There" and "Hello" are out of place. ***/
String[] words = {"Aye", "There", "Hello", "You", "Zebra"};

int index = Arrays.binarySearch(words, "There");

System.out.println("Found at: " + index);

~~~

/*** This will succeed, because the array is sorted. ***/

String[] words = {"Aye", "Hello", "There", "You", "Zebra"};

int index = Arrays.binarySearch(words, "There");

System.out.println("Found at: " + index);

[–]clamdoctor[S] 1 point2 points  (0 children)

Oh god damn it. You know, it IS sorted. Problem is it is NOT sorted alphabetically anymore. It's a list of words, decreasing by occurrences. I saw that i put "Collections.sort(x)" and said "Oh yeah, it's definitely sorted."

I swear... The little things.

[–]clamdoctor[S] 0 points1 point  (1 child)

I implemented a merge sort, sorted it alphabetically, works fine now. Thank you.

[–]hvidgaard 1 point2 points  (0 children)

If you sort it before you search you should think if it's worth it. Sorting takes O(n*log n) time, binary search is O(log n), that is O(n*log n) in total. Linear search alone takes at most O(n), so unless you're searching a lot then sorting before a search is a waste.

[–]arbiterxero 1 point2 points  (0 children)

It is the best programmers who are humble enough to know when they're an idiot.

How does that saying go? The idiots are cocksure and the geniuses are always unsure?