Advertisement
Statev

BinarySearch

Dec 25th, 2011
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.81 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4.  
  5. namespace _11.BinarySearch
  6. {
  7.     class BinarySearch
  8.     {
  9.         static int BinaryIndexFinder(int[] array, int key)
  10.         {
  11.             int downBorder = 0;
  12.             int upBorder = array.Length - 1;
  13.             while (true)
  14.             {
  15.                 int marker = (upBorder + downBorder) / 2;
  16.  
  17.                 if (marker == downBorder)
  18.                 {
  19.                     if (key == array[upBorder])
  20.                     {
  21.                         return upBorder;
  22.                     }
  23.                     else if (key == array[downBorder])
  24.                     {
  25.                         return downBorder;
  26.                     }
  27.                     else
  28.                     {
  29.                         break;
  30.                     }
  31.                 }
  32.  
  33.                 if (key > array[marker])
  34.                 {
  35.                     downBorder = marker + 1;
  36.                 }
  37.                 else if (key < array[marker])
  38.                 {
  39.                     upBorder = marker - 1;
  40.                 }
  41.                 else
  42.                 {
  43.                     return marker;
  44.                 }
  45.             }
  46.             return -1;
  47.         }
  48.  
  49.         static void Main(string[] args)
  50.         {
  51.             int[] array = {-10, -6, -3, -1, 1, 3, 5, 10, 12, 13, 18, 21};
  52.             Array.Sort(array);
  53.             Console.Write("Enter a number: ");
  54.             int number = int.Parse(Console.ReadLine());
  55.             int index = BinaryIndexFinder(array, number);
  56.  
  57.             if (index == -1)
  58.             {
  59.                 Console.WriteLine("Number is not find in the array");
  60.             }
  61.             else
  62.             {
  63.                 Console.WriteLine("Index of number: {0}", index);
  64.             }
  65.         }
  66.     }
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement