SHARE
TWEET

Bynary Search

Ludmil Jul 3rd, 2013 68 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. //11. Write a program that finds the index of given element in a
  2. //sorted array of integers by using the binary search algorithm (find it in Wikipedia).
  3. using System;
  4.  
  5. class Program
  6. {
  7.     static void Main()
  8.     {
  9.         int[] arr = { -8, -6, -1, 2, 3, 4, 6, 8 }; // arr ---- >
  10.         int searched =-8;
  11.         int decreaceInd = 0;
  12.         int increaceInd = arr.Length - 1;
  13.         int midIndex = 0;
  14.         int midlElValue = int.MinValue;
  15.  
  16.         int left = int.MinValue;
  17.         int right = int.MaxValue;
  18.  
  19.         while (midlElValue != searched)
  20.         {
  21.             midIndex = (decreaceInd + increaceInd) / 2; // arr[decrInd---?--mid index ---?--incrInd>>>]
  22.                                              //decreaceInd = decreaceInd + (increaceInd) / 2;
  23.             midlElValue = arr[midIndex];
  24.             if (midlElValue > searched) // arr[----?--------mid index----->]
  25.             {                               // so search in <--- this direction  use
  26.                 increaceInd = midIndex-1;// -1 to start from next index
  27.  
  28.                 right = arr[increaceInd]; // bonus
  29.            
  30.             }                           // arr[ decrId(same) ------?---mid Index----incrInd(midIndex-1)>>>>]
  31.             if (midlElValue < searched)// arr[--------mid index---?----->]
  32.             {                            //arr[ decrId(midIndex+1) ------?---mid Index----incrInd(same)>>>>]
  33.                 decreaceInd = midIndex + 1;
  34.  
  35.                 left = arr[decreaceInd];//bonus
  36.             }
  37.  
  38.             if (left < searched && searched > right)
  39.             {
  40.                 Console.WriteLine("value {0} not amember in arr",searched);
  41.             }
  42.         }
  43.         Console.WriteLine("Searched El {0}  index in arr [{1}]", searched, midIndex);              
  44.  
  45.     }
  46. }
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