Advertisement
vlad0

array 11

Jan 10th, 2013
34
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.68 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5.  
  6. //Write a program that finds the index of given
  7. //element in a sorted array of integers by using
  8. //the binary search algorithm (find it in Wikipedia).
  9.  
  10.  
  11. namespace _11.BinarySearch
  12. {
  13.     class BinarySearch
  14.     {
  15.         static void Main(string[] args)
  16.         {
  17.             //create 100 numbers sorted array to test
  18.             int[] myArray = new int[100];
  19.             for (int i = 0; i < 100; i++)
  20.             {
  21.                 myArray[i] = i+1 ; //testing with different numbers
  22.             }
  23.  
  24.            
  25.  
  26.             int indexMax=myArray.Length-1;
  27.             int indexMin=0;
  28.             int indexMiddle;
  29.            
  30.             bool isSearching=true; //if it is still searching is true
  31.  
  32.             Console.Write("Enter number between 1-100: ");
  33.             int searchKey = int.Parse(Console.ReadLine());
  34.            
  35.             while (isSearching)
  36.             {
  37.                 indexMiddle = (indexMin + indexMax) / 2;
  38.                 if (myArray[indexMiddle] < searchKey)
  39.                 {
  40.                     indexMin = indexMiddle + 1;
  41.                 }
  42.                 else if (myArray[indexMiddle] > searchKey)
  43.                 {
  44.                     indexMax = indexMiddle - 1;
  45.                 }
  46.                 else
  47.                 {
  48.                     Console.WriteLine("The position of the searching key <{0}> is: {1}", searchKey, indexMiddle);
  49.                     Console.WriteLine("The number on position [{0}] is equal to  :{1}", indexMiddle, myArray[indexMiddle]);
  50.                     isSearching = false;
  51.                 }
  52.             }
  53.  
  54.  
  55.         }
  56.     }
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement