I have a sorted array of 5000 integers. How fast can I tell if a random integer is a member of the array? An answer in general, C and Ruby would be nice.
The array values are of the form
c * c + 1
where c
can be any integer from 1 to 5000.
For example:
[2, 5, 10, 17, 26, 37, 50 ...]
Best Solution
Binary search, as others have mentioned, is O(log2N), and can be coded either recursively:
or iteratively:
However, if you're looking for the fastest possible way, you can set up a look up table based on the
sqrt(N-1)
of your numbers. With just 5,000 words of memory you can achieve O(1) lookups this way.Explanation:
Since all your numbers are of the form N^2 + 1 for an integer N from 1 to N, you can create a table of N elements. The element at position i will specify if i^2 + 1 is in your array or not. The table can be implemented with a simple array of length N. It will take O(N) to build, and N words of space. But once you have the table, all lookups are O(1).
Example:
Here's sample code in Python, which reads like pseudocode, as always :-)
Building the table takes up O(N) at most, and lookups are O(1).