Advertisement
Hristo_B

Binary Search

Jul 15th, 2013
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.98 KB | None | 0 0
  1. using System;
  2.  
  3. class BinarySearch
  4. {
  5.     static void Main()
  6.     {
  7.         //Write a program that finds the index of given element
  8.         //in a sorted array of integers by using the binary search algorithm (find it in Wikipedia).
  9.  
  10.         int[] arr = { 1, 3, 4, 8, 12, 13, 33, 48, 100, 25425, 24234111 };
  11.         foreach (int item in arr)
  12.         {
  13.             Console.Write(item + " ");
  14.         }
  15.         Console.WriteLine("\n");
  16.  
  17.         Console.WriteLine("Choose a number from the array given above!");
  18.         int searchedNum = int.Parse(Console.ReadLine());
  19.  
  20.         int max = arr.Length-1;
  21.         int min = 0;
  22.  
  23.         for (int i = 0; i < arr.Length; i++)
  24.         {
  25.             if (searchedNum != arr[i])
  26.             {
  27.                 Console.WriteLine("Your number doesn't appear to be in the array!");
  28.                 return;
  29.             }
  30.         }
  31.  
  32.         if (max < min)
  33.         {
  34.             Console.WriteLine("The array is empty");
  35.             return;
  36.         }
  37.         else
  38.         {
  39.            
  40.             bool numberFound = false;
  41.             while (numberFound != true)
  42.             {
  43.                 int middle = (max + min) / 2;
  44.                 if (arr[middle] > searchedNum)
  45.                 {
  46.                     max = middle;
  47.                     continue;
  48.                 }
  49.                 else if (arr[middle] < searchedNum)
  50.                 {
  51.                     min = middle;
  52.                     continue;
  53.                 }
  54.                 else if (arr[middle] == searchedNum)
  55.                 {
  56.                     Console.WriteLine("I found it!!!!");
  57.                     numberFound = true;
  58.                     Console.WriteLine("Your number - {0} is placed on {1} position",searchedNum, middle);
  59.                 }
  60.                 else
  61.                 {
  62.                     Console.WriteLine("Your number doesn't appear to be in the array!");
  63.                    
  64.                 }
  65.             }
  66.            
  67.         }
  68.  
  69.     }
  70. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement