Given a List<int> myValues
which I know to be ordered, what is the quickest way to determine if X
is 开发者_JAVA百科in the given list?
Do I really have to write my own binary search?
I think you can use list.Contains(value)
, but if you really need binary search list already has it implemented: list.BinarySearch()
.
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)]);
The simplest way to search through a list is Contains
:
if (myValues.Contains(x)) {
Though this only performs a linear search, which means that the execution time is depending on the size of the list and if the item is found at the beginning of the list or at the end.
A true binary search can be done with BinarySearch
. For a binary search to work the element should implement it's own comparison method (implementing IComparable<T>
), or you provide the search with a comparer.
if (myValues.BinarySarch(x)) {
精彩评论