15,904,153 members
See more:
I am putting together code but I am doing something wrong. I need to open a file of arrays, ask the user to input what number they want to search for, then complete a linear search, reload file, and sort to do a binary search.
My problem is when I enter numbers not included in the search its saying that the number is found(which is wrong). Any suggestions on what I might be doing wrong. The code Im having trouble with is listed below. This is part of the main code

C#
```int a = -1;
bs.Binary(unsorted, searchvalue);
if (a == -1)
else
Console.Out.WriteLine("Element " + searchvalue + " was found.");
```

This is the implementation file

C#
```    class LinearSearch<T>
{
public bool Linear(int[] A, int sv)
{
int count = 0;
for (int i = 0; i < A.Length - 1; i++)
{
count++;
if (sv == A[i])
return true;
}
return false;
}   //Linear()
}

class BinarySearch<T>
{
public int Binary(int[] A, int sv)
{
int size = 100;
int left = 0;
int right = size - 1;
while (left <= right)
{
int midpoint = (left + right) / 2;
// check to see if value is equal to item in array
if (sv == A[midpoint])
{
return sv;
}
else if (A[midpoint] > sv)
{
right = midpoint - 1;
}
else
left = midpoint + 1;
}
return -1;
}// Binary
}
}```

[Removed duplicate code snippet - Henry]
Posted
Updated 23-Nov-10 5:30am
v2

## Solution 1

Firstly, you don't need the "count" variable in you linear search - you do nothing with it.

Secondly: you should use the Length of the array A, rather than the magic number "100" in your binary search. What happens if there are 50 elements? What if there are 200?

Other than that, you code looks like it should work (ignoring the <T> part you aren't using). Are you sure your sort is working properly?

Tanacia 24-Nov-10 1:45am
yes its actually working fine. This is the only problem I am having. I didnt think about using a.length. That helped with an error I was getting because my file had 50 arrays. So thanks

## Solution 2

As OriginalGriff has said your search code looks fine to me.

The results you are getting do not make sense though as whatever number you search for should come up as NOT found.

In your calling code you assign `a` the value -1, but thereafter it is not changed. So a small change should cure this:
C#
```int a = bs.Binary(unsorted, searchvalue);  //<======= CHANGED ============
if (a == -1)
else
Console.Out.WriteLine("Element " + searchvalue + " was found.");```

Tanacia 24-Nov-10 1:48am
That did it! You rock Henry Minute!!!

## Solution 3

That did it!
You rock Henry!!!