Last active
August 29, 2015 14:17
-
-
Save ioab/d8121d541bf4e25fffc5 to your computer and use it in GitHub Desktop.
BinarySearch Algorithm
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
| /** | |
| * @note: | |
| * Works properly with numbers. | |
| * other types may have to define another equality criteria. | |
| * | |
| * @return: Item index if found. -1 otherwise. | |
| */ | |
| template<typename T> | |
| int BinarySearch(T * arr, int size, T searchKey) | |
| { | |
| int first = 0, | |
| last = size - 1, | |
| m = 0; // middle | |
| while (first <= last) | |
| { | |
| m = (first + last) / 2; | |
| if (arr[m] == searchKey) | |
| { | |
| return m; | |
| } | |
| else if (arr[m] < searchKey) | |
| { | |
| first = m + 1; | |
| } | |
| else | |
| { | |
| last = m - 1; | |
| } | |
| } | |
| return -1; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment