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
Sam HobbsPosted Dec 21, 2011, 1:54 PM
Posted Dec 21, 2011, 9:17 AM
VulpesPosted Dec 21, 2011, 8:49 AM
I've jumbled up the 4 zips we have to show that this still works:
Posted Dec 21, 2011, 8:14 AM
VulpesPosted Dec 21, 2011, 5:14 AM
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 20, 2011, 6:40 PM
VulpesPosted Dec 20, 2011, 6:31 PM
Notice that I've rearranged the zips array so that the elements are now in ascending order: