SHARE
TWEET

02.01.11.BinarySearch

stanevplamen Jul 2nd, 2013 46 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. using System;
  2.  
  3. class BinarySearch
  4. {
  5.     static void Main()
  6.     {
  7.         int[] intArray = { 2, 4, 5, 6, 8, 10, 12, 15 };
  8.         Array.Sort(intArray);
  9.         int firstMember = 0;
  10.         int lastMember = intArray.Length - 1;
  11.         int midMember = (firstMember + lastMember) / 2;
  12.  
  13.         int target = 10;    // The index should be found for this element
  14.         int index = -1;     // here will be copy the requested index of target
  15.  
  16.         while (lastMember >= firstMember)
  17.         {
  18.             midMember = (firstMember + lastMember) / 2;
  19.  
  20.             if (intArray[midMember] < target)
  21.             {
  22.                 // change min index to search upper subarray part
  23.                 firstMember = midMember + 1;
  24.             }
  25.             else if (intArray[midMember] > target)
  26.             {
  27.                 // change max index to search lower subarray part
  28.                 lastMember = midMember - 1;
  29.             }
  30.             else
  31.             {
  32.                 index = midMember;
  33.                 break;
  34.             }
  35.         }
  36.         if (index >= 0)
  37.         {
  38.             Console.WriteLine("The requestred number {0} is at index {1}", target, index);
  39.         }
  40.         else if (index < 0)
  41.         {
  42.             Console.WriteLine("The index of the requestred number {0} was not found", target);
  43.         }
  44.     }
  45. }
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