Last active
February 13, 2017 18:00
-
-
Save sebagomez/52bc255a8f851a5d5cba0d5e7a6d5179 to your computer and use it in GitHub Desktop.
C# Binary Search implementation
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
const int NOT_FOUND = -1; | |
static int Find(int[] arr, int num) | |
{ | |
if (arr.Length == 0) | |
return NOT_FOUND; | |
if (arr.Length == 1) | |
return arr[0] == num ? 0 : NOT_FOUND; | |
int m = arr.Length / 2; | |
if (arr[m] == num) | |
return m; | |
int k = NOT_FOUND; | |
if (arr[m] > num) | |
k = Find(arr.Take(m).ToArray(), num); | |
else | |
{ | |
k = Find(arr.Skip(m).ToArray(), num); | |
k = k == NOT_FOUND ? NOT_FOUND : (k + m); | |
} | |
return k; | |
} | |
static int NonRecursiveFind(int[] arr, int num) | |
{ | |
int start = 0; | |
int end = arr.Length - 1; | |
while (start != end) | |
{ | |
int m = (start + end) / 2; | |
if (arr[m] == num) | |
return m; | |
if (arr[m] > num) | |
end = m; | |
else | |
start = m; | |
} | |
return NOT_FOUND; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment