Skip to content

Instantly share code, notes, and snippets.

@HojjatK
Created October 14, 2018 05:20
Show Gist options
  • Save HojjatK/fb811251b62a66f665beeeaa570e9100 to your computer and use it in GitHub Desktop.
Save HojjatK/fb811251b62a66f665beeeaa570e9100 to your computer and use it in GitHub Desktop.
Binary Search Algorithem
/// <summary>
/// Binary search splits the search data field into two sections recursivley to find the search target.
/// It already assumes the items are sorted.
/// O(log n)
/// </summary>
public class BinarySearch
{
public int Find<T>(IList<T> sortedList, T target) where T : IComparable<T>
{
var n = sortedList.Count;
int min = 0, max = n;
while(min <= max && n != 0)
{
int mid = (min + max) / 2;
var comp = target.CompareTo(sortedList[mid]);
if (comp == 0)
{
// current element == target
return mid;
}
if (comp < 0)
{
// target < current element
max = mid - 1;
}
else
{
// target > current element
min = mid + 1;
}
}
return -1;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment