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
*/
Loading

VulpesRank #55 · 29.2K reputationPosted Dec 20, 2011, 1:31 PM EST
Notice that I've rearranged the zips array so that the elements are now in ascending order:
Posted Dec 20, 2011, 1:40 PM EST
VulpesRank #55 · 29.2K reputationPosted Dec 21, 2011, 12:14 AM EST
http://msdn.microsoft.com/en-us/library/35f0x18w.aspx
This method uses what's called a 'word' comparison, which is both case sensitive and culture sensitive, using the current culture.
Broadly, for where you are, I'd expect this to be alphabetic order with lower case letters preceding upper case letters. That's why I moved the string beginning with "BK" to be between those starting with "BF" and "GJ".
Posted Dec 21, 2011, 3:14 AM EST
VulpesRank #55 · 29.2K reputationPosted Dec 21, 2011, 3:49 AM EST
I've jumbled up the 4 zips we have to show that this still works:
Posted Dec 21, 2011, 4:17 AM EST
Sam HobbsRank #107 · 20.5K reputationPosted Dec 21, 2011, 8:54 AM EST