SHARE
TWEET

Binary Search

enevlogiev May 18th, 2015 241 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. using System;
  2. using System.Linq;
  3.  
  4. class BinarySearch
  5. {
  6.     static void Main()
  7.     {
  8.         int[] numbers = Console.ReadLine().Split().Select(int.Parse).ToArray();
  9.         int search = int.Parse(Console.ReadLine());
  10.  
  11.         int index = CustomBinarySearch(numbers, 0, numbers.Length - 1, search);
  12.         if (index < 1)
  13.         {
  14.             Console.WriteLine(index);
  15.         }
  16.         else
  17.         {
  18.             index = CheckIfLeftmost(numbers, index);
  19.             Console.WriteLine(index);
  20.         }
  21.  
  22.     }
  23.  
  24.     static int CustomBinarySearch(int[] arr, int min, int max, int keyValue)
  25.     {
  26.         int middleIndex = (min + max) / 2;
  27.         if (min >= max && arr[middleIndex] != keyValue)
  28.         {
  29.             return -1;
  30.         }
  31.         if (arr[middleIndex] == keyValue)
  32.         {
  33.             return middleIndex;
  34.         }
  35.         if (keyValue < arr[middleIndex])
  36.         {
  37.             return CustomBinarySearch(arr, min, middleIndex - 1, keyValue);
  38.         }
  39.         return CustomBinarySearch(arr, middleIndex + 1, max, keyValue);
  40.     }
  41.  
  42.     static int CheckIfLeftmost(int[] arr, int index)
  43.     {
  44.         int leftMost = index;
  45.         for (int i = index; i >= 1; i--)
  46.         {
  47.             if (arr[i] == arr[i - 1])
  48.             {
  49.                 leftMost = i - 1;
  50.             }
  51.         }
  52.  
  53.         return leftMost;
  54.     }
  55. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top