Advertisement
svetoslavbozov

[C#-2.1.11] BinarySearch

Jan 13th, 2013
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 0.75 KB | None | 0 0
  1. using System;
  2.  
  3. class BinarySearchAlgorithm
  4. {
  5.     static int BinarySearch(int[] array, int value)
  6.     {
  7.         int low = 0, high = array.Length - 1, midpoint = 0;
  8.  
  9.         while (low <= high)
  10.         {
  11.             midpoint = low + (high - low) / 2;
  12.  
  13.             if (value == array[midpoint])
  14.             {
  15.                 return midpoint;
  16.             }
  17.             else if (value < array[midpoint])
  18.                 high = midpoint - 1;
  19.             else
  20.                 low = midpoint + 1;
  21.         }
  22.         return -1;
  23.     }
  24.    
  25.     static void Main()
  26.     {
  27.         int[] array = { 1, 2, 3, 5, 6, 8, 1, 9, 0, 1, 4, 5, 6, 7, 8, 1, 1 };
  28.         int n = 9;
  29.         Array.Sort(array);
  30.         Console.WriteLine(BinarySearch(array, n));
  31.     }
  32. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement