问题
I have an array list of strings, the string are in sorted order, i want to find the index of a particular element, Which one will be faster?
- Performing indexOf() of lists
- Performing a binary search in an equivalent array?
回答1:
You can use Collections.binarySearch
directly for better efficience:
public static <T> int binarySearch(List<? extends Comparable<? super T>> list,
T key)
Searches the specified list for the specified object using the binary search algorithm. The list must be sorted into ascending order according to the natural ordering of its elements (as by the sort(List) method) prior to making this call. If it is not sorted, the results are undefined. If the list contains multiple elements equal to the specified object, there is no guarantee which one will be found.
This method runs in log(n) time for a "random access" list (which provides near-constant-time positional access). If the specified list does not implement the RandomAccess interface and is large, this method will do an iterator-based binary search that performs O(n) link traversals and O(log n) element comparisons.
While List.indexOf
runs in O(n) time, doesn't care about if the List is sorted or not.
回答2:
if its sorted then you should use binarysearch. binarySearch() will be O(log n) as opposed to indexOf()'s O(n)
回答3:
That depends on what exactly you are looking for. Let's say you have following strings in the Array list: "a","b","c","d","e","f","g","h","i" your binary search would work down a tree which could look like
e
/ \
c g
/ \ / \
b d f h
/ \
a i
So depending on which string you are searching for you get different amounts of tries until you find the right string. As the algorithm works it's way down from the top and compares wether the searched string is bigger or smaller then the string it is testing and depending on that checks the one to the left (smaller) or the one to the right (bigger)
How ever if you worl yourself down the line and you are not searching something that is at the beginning of your sorted list then the search will take longer.
回答4:
It's already mentioned that Binary Search is better as it is working with O(log n).
Another benefit is Collection.binarySearch(...) is it returns the position where it should be inserted. Thus, if you will do insertion operation, that is another advantage. Here is how it works:
int x = Collection.binarySearch(list, element);
if(x > 0)
System.out.println("it exists");
else
list.add(element, -x-1);
I don't know if you need this but I like it :)
来源:https://stackoverflow.com/questions/32495416/indexof-or-binary-search