Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fastest way to determine if an element is in a sorted array

I have an array of sorted ints with a 1,000 or more values (could be up to 5000+). I need to write a function that receives an int and returns a bool based on the element being in the array. I know I can write a for loop with a break, I know I can use jquery .InArray.

What would be the best way to implement this, KNOWING that the array is sorted.

Thanks.

like image 657
frenchie Avatar asked Apr 22 '12 00:04

frenchie


People also ask

Which search is best for sorted array?

If we know nothing about the distribution of key values, then we have just proved that binary search is the best algorithm available for searching a sorted array.

How do you check elements are sorted or not?

The C++ function std :: is_sorted checks if the elements in range [first, last] are sorted in ascending order.


1 Answers

Knowing that the array is sorted a binary search would be the best approach.

like image 102
g.d.d.c Avatar answered Sep 20 '22 15:09

g.d.d.c