Created
October 14, 2018 05:20
-
-
Save HojjatK/fb811251b62a66f665beeeaa570e9100 to your computer and use it in GitHub Desktop.
Binary Search Algorithem
This file contains hidden or 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
/// <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