Maha

Maha

  • NA
  • 0
  • 326k

BinarySearch

Dec 20 2011 6:19 PM
Following example shows BinarySearch in the numerical array. If the array is string how to do a BinarySearch following the same method. For example string[] zips = { "BF 45633", "GJ 76895", "BK 87946", "NM 38657" };


using System;
public class BinarySearchDemo
{
public static void Main()
{
int[] idNumbers = { 122, 167, 204, 219, 345 };
//idNumbers must be in ascending order to perform a BinarySearch.

int x;
string entryString;
int entryId;

Console.Write("Enter an Employee ID: ");

entryString = Console.ReadLine();
entryId = Convert.ToInt32(entryString);

x = Array.BinarySearch(idNumbers, entryId);

if (x < 0)
Console.WriteLine("ID {0} not found", entryId);
else
Console.WriteLine("ID {0} was found at position {1}", entryId, x);

/*The method returns -1 if the value is not
found in the array; otherwise, it returns
the array position of the sought value */

}
}
/*
Enter an Employee ID: 219
ID 219 was found at position 3

Enter an Employee ID: 122
ID 122 was found at position 0

Enter an Employee ID: 888
ID 888 not found
*/


Answers (7)