SHARE
TWEET

C# Arrays Binary Search

Ms_Nenova Jan 16th, 2013 59 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. using System;
  2.  
  3. class BinarySearch //source - wikipedia
  4. {
  5.     static void Main()
  6.     {
  7.         int[] arr = { 7, 12, 46, 2, 6, 24, 218, -5 };
  8.         Console.Write("Choose a value from {0}:", string.Join(", ", arr));
  9.         int value = int.Parse(Console.ReadLine());
  10.  
  11.         Array.Sort(arr);
  12.         int minIndex = 0;
  13.         int maxIndex = arr.Length - 1;
  14.  
  15.         while (maxIndex >= minIndex)
  16.         {
  17.             int midIndex = (maxIndex + minIndex) / 2;
  18.             // determine which subarray to search
  19.             if (arr[midIndex] < value)
  20.             {
  21.                 // change min index to search upper subarray
  22.                 minIndex = midIndex + 1;
  23.             }
  24.             else if (arr[midIndex] > value)
  25.             {
  26.                 // change max index to search lower subarray
  27.                 maxIndex = midIndex - 1;
  28.             }
  29.             else
  30.             {
  31.                 value = midIndex;
  32.             }            
  33.         }
  34.         Console.WriteLine("Position {0} in this sorted array.", value);
  35.     }
  36. }
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