# Using a binary search for a single array of values [Answered]RSS

## 4 replies

Last post Oct 14, 2013 10:14 PM by AppDevForMe

• AppDevForMe

Participant

1157 Points

1367 Posts

### Using a binary search for a single array of values

I have an array of 20 numbers starting at 1 and ending at 100.

X[0]=1
X[1]=2
. .
X[99]=100.

My program will prompt for a random number to be entered. Once the number is entered, I need to find the array value which contains the number which was entered.

For example if someone enters the number 7, I will locate the array value which contains the number 7. So X[6] would be the answer.

Should I use a binary search to locate this value? I haven't every used a binary search before however I believe it might use recursion. I was thinking of a binary search, because the search needs to happen as fast as possible.

• Paul Linton

Star

9555 Points

2784 Posts

### Re: Using a binary search for a single array of values

Oct 13, 2013 01:49 AM|Paul Linton|LINK

If the number is N then the index is N-1

Got a c# problem? Try .NET Book Zero from Charles Petzold, it's a free pdf.
• AppDevForMe

Participant

1157 Points

1367 Posts

### Re: Using a binary search for a single array of values

Funny Paul, I awoke thinking the same thing and then realized that I over simplified the question. Because you see my array will also contain decimal values. Anyway, let me close out this question. Give you credit and then go back to the drawing board in regards to the best way to rephrase the question.

• Paul Linton

Star

9555 Points

2784 Posts

### Re: Using a binary search for a single array of values

Oct 13, 2013 04:56 PM|Paul Linton|LINK

I suspect that thmay be a better data structure to use than an array.  Does the same item appear more than once in the array?  Why do you want to know the index, what do you do with it?

My first reaction if I want to look something up is a structure that implements IDictionary.  (truth be told, I never use arrays if they can be avoided - it feels soooo 20th century )

Got a c# problem? Try .NET Book Zero from Charles Petzold, it's a free pdf.
• AppDevForMe

Participant

1157 Points

1367 Posts