SHARE
TWEET

Binary Search algorithm

a guest Jul 14th, 2013 34 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. using System;
  2.  
  3. namespace Task_11_BinarySearch
  4. {
  5. class Program
  6. {
  7. static void Main()
  8. {
  9.     int[] Arr = new int[10];
  10.     int WantedNumber;
  11.     int Start = 0;
  12.     int End = Arr.Length - 1;
  13.     int Mid = 0;
  14.     bool KeyFound = false;
  15.  
  16.     for (int i = 0; i < Arr.Length; i++)
  17.     {
  18.         Console.Write("Element {0}: ", i);
  19.         Arr[i] = int.Parse(Console.ReadLine());
  20.     }
  21.  
  22.     Console.Write("Please enter the digit you are looking for: ");
  23.     WantedNumber = int.Parse(Console.ReadLine());
  24.  
  25.     //Sort the array ascending and print it
  26.     Array.Sort(Arr);
  27.  
  28.     Console.Write("This is the sorted array: {");
  29.     for (int i = 0; i < Arr.Length; i++)
  30.     {
  31.         Console.Write(Arr[i] + " ");
  32.     }
  33.     Console.WriteLine("}");
  34.  
  35.     //Look for the wanted number
  36.     while (KeyFound == false)
  37.     {
  38.         Mid = Start + (End - Start) / 2;
  39.  
  40.         if (WantedNumber > Arr[Mid])
  41.         {
  42.             Start = Mid;
  43.             End = Mid + (Arr.Length - Mid) / 2;
  44.         }
  45.         if (WantedNumber < Arr[Mid])
  46.         {
  47.             Start = Mid / 2;
  48.             End = Mid;
  49.         }
  50.         if (WantedNumber == Arr[Mid])
  51.         {
  52.             Console.WriteLine("The index of the wanted number is: {0}! Wanted number: {1}", Mid, Arr[Mid]);
  53.             KeyFound = true;
  54.         }
  55.         if (WantedNumber == Arr[Mid + 1])
  56.         {
  57.             Console.WriteLine("The index of the wanted number is: {0}! Wanted number: {1}", Mid+1, Arr[Mid + 1]);
  58.             KeyFound = true;
  59.         }
  60.         if (WantedNumber == Arr[Mid - 1])
  61.         {
  62.             Console.WriteLine("The index of the wanted number is: {0}! Wanted number: {1}", Mid-1, Arr[Mid - 1]);
  63.             KeyFound = true;
  64.         }
  65.     }
  66. }
  67. }
  68. }
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