public static int contains(int[] list, int e)
{
for(int c = 0; c < list.length; c++)
{
if(list[c] == e)
return c;
}
return -1;
}
This method will return the index of the first occurrence of e if it is in list. If e is not in list, then it will return -1. We know this is correct, because e will be compared to every element in list. If, after that, we still haven't found an instance of e, then it is not in the list. It runs in O(n) time.
Of course, if we want a fast search, we'd use the binary search, which runs in O(log n) time. There's only 1 catch: The list has to be sorted first, which would take, on average with the fastest algorithms (quick or merge) , O(n log n) time. So if it's not sorted, go ahead and use the iterative search. Unless you are going to be doing a lot of searching in a large list that isn't going to change (like a dictionary), in which case sort first and use the binary search. And of coarse, the data you are searching has to be comparable in a greater-then/less-than way. In Java this includes any primitive data type, strings and objects implementing the Comparable interface.
public static int binarySearch(int[] list, int e)
{
int beg = 0;
int end = list.length - 1;
while (beg <= end)
{
int mid = (end - mid)/2;
if(list[mid] == e)
return mid;
if(list[mid] > e)
end = mid - 1;
else
beg = mid + 1;
}
return -1;
}
Again, if e is in list, the algorithm will return the index it is at, thought this time it will not necessarily the first occurrence e in the list. If e is not in list, it will return -1. As I said before, the list MUST be sorted first, or this will NOT work.