Count number of comparisons made for BinarySearch
algorithm, c#, count, search
Solution
You can use this extension method (code based on this answer)
public static class ListEx
{
public static Tuple<int, int> BinarySearchWithCount<T>(
this IList<T> list, T key)
{
int min = 0;
int max = list.Count - 1;
int counter = 0;
while (min <= max)
{
counter++;
int mid = (min + max) / 2;
int comparison = Comparer<T>.Default.Compare(list[mid], key);
if (comparison == 0)
{
return new Tuple<int, int>(mid, counter);
}
if (comparison < 0)
{
min = mid + 1;
}
else
{
max = mid - 1;
}
}
return new Tuple<int, int>(~min, counter);
}
}
//Which returns a tuple with the item and a number of comparisons.
//Here is how you can use it:
class Program
{
static void Main(string[] args)
{
var numbers = new List<int>();
numbers.AddRange(Enumerable.Range(0, 100000));
var answer = numbers.BinarySearchWithCount(2);
Console.WriteLine("item: " + answer.Item1); // item: 2
Console.WriteLine("count: " + answer.Item2); // count: 15
}
}
Problem
I have the task of creating two seperate programs, one linear search program, which I have already completed, and a binary search program. These programs must also count the number of comparisons made during the search process. My linear search program already counts the number of comparisons made while my binary search program cannot. The code for the binary search looks like this: ``` using System; using System.Collections.Generic; public class Example { public static void Main() { Console.WriteLine("Input number you would like to search for"); String Look_for = Console.ReadLine(); int Lookfor; int.TryParse(Look_for, out Lookfor); { List<int> numbers = new List<int>(); numbers.Add(1); numbers.Add(2); numbers.Add(3); numbers.Add(4); numbers.Add(5); numbers.Add(6); numbers.Add(7); numbers.Add(8); Console.WriteLine(); foreach (int number in numbers) { Console.WriteLine(number); } int answer = numbers.BinarySearch(Lookfor); Console.WriteLine("The numbers was found at:"); Console.WriteLine(answer); } } } ``` If anybody can tell me how to modify it to count comparisons it would be greatly appreciated. Many thanks, Matthew.