Created
January 27, 2021 21:19
-
-
Save Swimburger/4f7cbfcff77e9d3d7dfa86dde05883dc to your computer and use it in GitHub Desktop.
Generic BinarySearch in C#
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
var numbers = Enumerable.Range(0, 1000).ToArray(); | |
Console.WriteLine("Binary Search:"); | |
var index = BinarySearch(numbers, 183); | |
Console.WriteLine(index); | |
Console.ReadKey(); | |
Console.Clear(); | |
} | |
private static int BinarySearch<T>(IEnumerable<T> list, T needle) where T : IComparable | |
{ | |
int left = 0; | |
int right = list.Count() - 1; | |
while (left <= right) | |
{ | |
int median = (left + right) / 2; | |
T item = list.ElementAt(median); | |
var comparison = needle.CompareTo(item); | |
if(comparison == 0) | |
{ | |
return median; | |
} | |
if (comparison < 0) | |
{ | |
right = median - 1; | |
} | |
else | |
{ | |
left = median + 1; | |
} | |
} | |
return -1; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment