TECHNOLOGIES
FORUMS
JOBS
BOOKS
EVENTS
INTERVIEWS
Live
MORE
LEARN
Training
CAREER
MEMBERS
VIDEOS
NEWS
BLOGS
Sign Up
Login
No unread comment.
View All Comments
No unread message.
View All Messages
No unread notification.
View All Notifications
Answers
Post
An Article
A Blog
A News
A Video
An EBook
An Interview Question
Ask Question
Forums
Monthly Leaders
Forum guidelines
Maha
NA
0
324k
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
*/
Reply
Answers (
7
)
Designing a Console Editor
Indexer in C#