Advertisement
sylviapsh

Binary search algorithm find Element Index(sorted array)

Jan 10th, 2013
42
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.18 KB | None | 0 0
  1. using System;
  2. class BinarySearchAlgorithm
  3. {
  4.   static void Main()
  5.   {
  6.     //Write a program that finds the index of given element in a sorted array of integers by using the binary search algorithm (find it in Wikipedia).
  7.  
  8.     int[] searchArray = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 };
  9.     Array.Sort(searchArray);
  10.  
  11.     int numToSearch = 8,
  12.         startSearchIndex = 0,
  13.         endSearchIndex = searchArray.Length-1,
  14.         currentMiddle = 0;
  15.     bool foundFlag = false;
  16.  
  17.     while (startSearchIndex <= endSearchIndex)
  18.     {
  19.       currentMiddle = (startSearchIndex + endSearchIndex)/2;
  20.  
  21.       if (searchArray[currentMiddle] == numToSearch)
  22.       {
  23.         Console.WriteLine("The index of the searched number {0} is: {1}", numToSearch, currentMiddle);
  24.         foundFlag = true;
  25.         break;
  26.       }
  27.       else if (searchArray[currentMiddle] < numToSearch)
  28.       {
  29.         startSearchIndex = currentMiddle + 1;
  30.       }
  31.       else
  32.       {
  33.         endSearchIndex = currentMiddle - 1;
  34.       }
  35.     }
  36.  
  37.     if (foundFlag == false)
  38.       {
  39.         Console.WriteLine("Number {0} not found in the array!", numToSearch);
  40.       }
  41.   }
  42. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement