Last active
July 2, 2019 18:43
-
-
Save takint/fc0855167b1ad8f5ed5fc1fcf8f2891c to your computer and use it in GitHub Desktop.
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
// Iterative | |
static int BinarySearch(int[] arr, int value) | |
{ | |
int left = 0; | |
int right = arr.Length - 1; | |
while (left <= right) | |
{ | |
int mid = left + (right - left) / 2; | |
if (arr[mid] == value) | |
{ | |
return mid; | |
} | |
else if (value > arr[mid]) | |
{ | |
left = mid + 1; | |
} | |
else | |
{ | |
right = mid - 1; | |
} | |
} | |
return -1; | |
} | |
// Recursive | |
static int BinarySearch(int[] arr, int left, int right, int value) | |
{ | |
if (left <= right) | |
{ | |
int mid = left + (right - left) / 2; | |
if (arr[mid] == value) | |
{ | |
return mid; | |
} | |
else if (value > arr[mid]) | |
{ | |
return BinarySearch(arr, mid + 1, right, value); | |
} | |
else | |
{ | |
return BinarySearch(arr, left, mid - 1, value); | |
} | |
} | |
return -1; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment