Advertisement
simonses

BinarySearchFindElement

Jan 12th, 2013
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.38 KB | None | 0 0
  1. using System;
  2.  
  3. class BinarySearchFindElement
  4. {
  5.     static int BinarySearch(int[] array, int getIndex)
  6.     {
  7.         int iMin = 0;
  8.         int iMax = array.Length - 1;
  9.         // continue searching while [imin,imax] is not empty
  10.         while (iMax >= iMin)
  11.         {
  12.             /* calculate the midpoint for roughly equal partition */
  13.             int iMid = (iMax + iMin) / 2;
  14.  
  15.             // determine which subarray to search
  16.             if (array[iMid] < getIndex)
  17.                 // change min index to search upper subarray
  18.                 iMin = iMid + 1;
  19.             else if (array[iMid] > getIndex)
  20.                 // change max index to search lower subarray
  21.                 iMax = iMid - 1;
  22.             else
  23.                 // key found at index imid
  24.                 return iMid;
  25.         }
  26.         // key not found
  27.         return -1;
  28.     }
  29.  
  30.  
  31.     static void Main()
  32.     {
  33.         int[] myArray = { -10, -8, -3, 0, 1, 1, 2, 3, 5, 10, 10, 25, 26, 30, 31, 33, 38, 40};
  34.         int number = 26;
  35.         // int number = 34;  // Return that the number is not found
  36.  
  37.         if (BinarySearch(myArray, number) == -1)
  38.         {
  39.             Console.WriteLine("The searching number \"{0}\" is not found in the array!", number);
  40.         }
  41.         else
  42.         {
  43.             Console.WriteLine("The index of number is: " + BinarySearch(myArray, number));
  44.         }
  45.     }
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement