Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- namespace binary_search
- {
- internal class Program
- {
- static void Main(string[] args)
- {
- int[] array = new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 };
- int target = 8;
- int itterativePos = ItterativeBinarySearch(array, target);
- Console.WriteLine(itterativePos);
- int recursivePos = RecursiveBinarySearch(array, target);
- Console.WriteLine(recursivePos);
- }
- private static int RecursiveBinarySearch(int[] array, int target)
- {
- int l = 0, r = array.Length - 1;
- return RecursiveBinarySearch(array, target, l, r);
- }
- private static int RecursiveBinarySearch(int[] array, int target, int l, int r)
- {
- int m = (l + r) / 2;
- if (l > r)
- {
- return -1;
- }
- if (array[m] == target)
- {
- return m;
- }
- if (array[m] > target)
- {
- r = --m;
- }
- if (array[m] < target)
- {
- l = ++m;
- }
- return RecursiveBinarySearch(array, target, l, r);
- }
- private static int ItterativeBinarySearch(int[] array, int target)
- {
- int l = 0, r = array.Length - 1;
- while (l <= r)
- {
- int m = (l + r) / 2;
- if (array[m] == target)
- {
- return m;
- }
- else if (array[m] > target)
- {
- r = --m;
- }
- else// if (array[m] < target)
- {
- l = ++m;
- }
- }
- return -1;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment