Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- //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).
- namespace _11.BinarySearch
- {
- class BinarySearch
- {
- static void Main(string[] args)
- {
- //create 100 numbers sorted array to test
- int[] myArray = new int[100];
- for (int i = 0; i < 100; i++)
- {
- myArray[i] = i+1 ; //testing with different numbers
- }
- int indexMax=myArray.Length-1;
- int indexMin=0;
- int indexMiddle;
- bool isSearching=true; //if it is still searching is true
- Console.Write("Enter number between 1-100: ");
- int searchKey = int.Parse(Console.ReadLine());
- while (isSearching)
- {
- indexMiddle = (indexMin + indexMax) / 2;
- if (myArray[indexMiddle] < searchKey)
- {
- indexMin = indexMiddle + 1;
- }
- else if (myArray[indexMiddle] > searchKey)
- {
- indexMax = indexMiddle - 1;
- }
- else
- {
- Console.WriteLine("The position of the searching key <{0}> is: {1}", searchKey, indexMiddle);
- Console.WriteLine("The number on position [{0}] is equal to :{1}", indexMiddle, myArray[indexMiddle]);
- isSearching = false;
- }
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement