Advertisement
Teodor92

11. BinSearch

Jan 6th, 2013
935
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 0.94 KB | None | 0 0
  1. /* Write a program that finds the index of
  2.  * given element in a sorted array of integers
  3.  * by using the binary search algorithm (find it in Wikipedia).
  4.  */
  5.  
  6. using System;
  7.  
  8. class BinarySearch
  9. {
  10.     static int BinSearch(int[] array, int key)
  11.     {
  12.         Array.Sort(array);
  13.         int iMax = array.Length - 1;
  14.         int iMin = 0;
  15.         while (iMax >= iMin)
  16.         {
  17.             int iMidpoint = (iMin + iMax) / 2;
  18.             if (array[iMidpoint] < key)
  19.             {
  20.                 iMin = iMidpoint + 1;
  21.             }
  22.             else if (array[iMidpoint] > key)
  23.             {
  24.                 iMax = iMidpoint - 1;
  25.             }
  26.             else
  27.             {
  28.                 return iMidpoint;
  29.             }
  30.         }
  31.         return -1;
  32.     }
  33.     static void Main()
  34.     {
  35.         int[] myArray = { 4, 3, 1, 4, 2, 5, 8, 21, 13, 180 };
  36.         int key = 8;
  37.         Console.WriteLine(BinSearch(myArray, key));
  38.     }
  39. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement