tags:

views:

73

answers:

3

Given a List<int> myValues which I know to be ordered, what is the quickest way to determine if X is in the given list?

Do I really have to write my own binary search?

+1  A: 

myValues.Contains(x)

Bobby
List<>.Contains() is a linear search so will be much slower than a binary search for larger lists (O(n) rather than O(log n).
Paul Ruane
+10  A: 

I think you can use list.Contains(value), but if you really need binary search list already has it implemented: list.BinarySearch().

Andrew Bezzub
Ah if only I'd tried the most obvious thing first. BinarySearch method is exactly what I was looking for! Thanks!
Dead account
+1  A: 

There's a binary search function provided:

List<int> myList = new List<int>() {314,1592,6535};
Console.WriteLine("{0}: {1}", myList.BinarySearch(6535), myList[myList.BinarySearch(6535)]);
BlueMonkMN