15,616,520 members
See more:
Hi guys
i want to know how can i print how many this code try to find the target
for example we have a list of numbers :

4,6,7,8,10,12,17,21

and we want to find 17

in that case we know linear search would be = 7 compare
and binary search sould be 3 compare i guess
so i want to print this 7 compare andd 3

for linear search i know what is the code but idk how to add it on binary search

idk if this code is right or not

What I have tried:

C#
// linear code
int[] number = new int[] {4,6,7,8,10,12,17,21};
int target = 17;
for (int i = 0; i < number.Length; i++)
{

if (number[i] == target)
{
Console.WriteLine("tries = {0}", i);

}

}

// binary code
C#
int[] number = new int[] {4,6,7,8,10,12,17,21};
int max = number.Length;
int min = 0;
int target = 17;
int try=0;

{

while (min<max)
{

try= try + 1;

int mid = (min + max) / 2;
if (number[mid] == target)
{

break;
}

else if (number[mid] > target)
{

max = mid - 1;

}
else if (number[mid] < target)
{

min = mid + 1;

}
else
{
}

}
}

Posted
Updated 10-Apr-22 22:25pm
v2
PIEBALDconsult 10-Apr-22 17:45pm
Looks reasonable, why do you think otherwise?

## Solution 1

Put your two searches into separate methods: LinearSearch and BinarySearch. Both methods have the same signature: they return an integer, and take an array of integers as a parameter, plus a "look for" value as well.

If they find the value, they return the number of tries.
If they don't find the value, they return -1 (just as String.IndexOf does).

Then call them both and save the results in separate variables, and it's easy to show your results.

In the methods it's easy to do as well: set a counter before the loop to 1, and increment it at the end of the loop. If you find the value, immediately return the counter.
If you reach the end of the method without finding the value, return -1:
C#
int LinearSearch(int[] data, int lookFor)
{
int tries = 1;
foreach (int x in data)
{
if (x == lookFor) return tries;
tries++;
}
return -1;
}
Use exactly the same pattern for BinarySearch and it is trivial to implement and easy to understand!