DEV Community

C++Love
C++Love

Posted on

Binary Search

A 16 line implementation of the binary search algorithm in C#.
Which I used to create an ASCII table!

Top comments (3)

Collapse
 
bluma profile image
Roman Diviš

Unfortunately this is not a valid binary search algorithm with log(n) complexity. left++ and right— changes search position by one and not by half of remaining items. You need to change left/right to middle+-1.

Collapse
 
startrekrules profile image
C++Love

Fixed..I think

Collapse
 
bluma profile image
Roman Diviš

Yes, now it can find any character (from your list) in maximally 8 steps...

You can also enhance code a little... There is no need to use IComparable as a parameter to the Search method. You have generics and thus it would be better to have the parameter of type T. You can specify that "T" is IComparable: public static int Search<T>(List<T> list, T val) where T : IComparable<T>