views:

397

answers:

4

Let's say I have a Java ArrayList, that is sorted. Now I would like to find the index of value x. What would be the fastest (without more than 30 lines of code) way to do this? Use of the IndexOf() method? Iterate through all values in a simple for loop? Use of some cool algorithm? We are talking about around let's say 50 integer keys.

+12  A: 

Binary search, but since it's only 50 items, who cares (unless you have to do it millions of times)? A simple linear search is simpler and the difference in performance for 50 items is negligible.

Edit: You could also use the built-in java.util.Collections binarySearch method. Be aware, that it will return an insertion point even if the item isn't found. You may need to make an extra couple of checks to make sure that the item really is the one you want. Thanks to @Matthew for the pointer.

tvanfosson
For fifty keys, I completely agree. Developer time is more important than CPU time these days. Use IndexOf() and be on your way.
John Feminella
Except that Java /has/ this functionality.
Matthew Flaschen
Binary search is the way to go. The list may currently only have 50 items, but who knows what the code will have to handle in a year or two..
Nils Pipenbrinck
@Matthew -- didn't know that -- been a while since I've written much Java, though I just started writing a small applet yesterday for a project that I'm working on. Will update.
tvanfosson
If the item is not found it returns (-(insertion point) - 1). So if you don't care about insertion points, just check if the return value is non-negative.
Matthew Flaschen
+6  A: 

tvanfosson is right, that the time for either will be very low, so unless this code runs very frequently it won't make much difference.

However, Java has built-in functionality for binary searches of Lists (including ArrayLists), Collections.binarySearch.

Matthew Flaschen
+1  A: 

If the keys have a acceptable distribution, Interpolation Search might be very fast way considering execution time.

Considering coding time IndexOf() is the way to go (or a built-in in binary search if availiable for your data type (I am from C# and don't know Java)).

Daniel Brückner
+2  A: 
import java.util.ArrayList;
import java.util.Collections;

ArrayList myList = new ArrayList();
// ...fill with values

Collections.sort( myList );
int index = Collections.binarySearch( myList, "searchVal" );

Edit: untested code

John Pirie
Thank you for the code :)
Baversjo