我的任务是创建两个单独的程序,一个我已经完成的线性搜索程序,以及一个二进制搜索程序。这些程序还必须计算在搜索过程中进行的比较次数。我的线性搜索程序已经计算了我的二进制搜索程序不能进行的比较次数。二进制搜索的代码如下所示:
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);
}
}
}
如果有人可以告诉我如何修改它来计算比较,我们将不胜感激。
非常感谢,马修。
答案 0 :(得分:5)
实施一个计算比较的IComparer<int>
:
private class CountComparer : IComparer<int> {
public int Count { get; private set; }
public CountComparer() {
Count = 0;
}
public int Compare(int x, int y) {
Count++;
return x.CompareTo(y);
}
}
然后在the overload of BinarySearch
that takes a comparer中将其用作比较器:
CountComparer comparer = new CountComparer();
int answer = numbers.BinarySearch(Lookfor, comparer);
然后比较器包含计数:
Console.WriteLine("The binary search made {0} comparisons.", comparer.Count);
奖金:任何类似类型的通用计数比较器:
private class CountComparer<T> : IComparer<T> where T : IComparable<T> {
public int Count { get; private set; }
public CountComparer() {
Count = 0;
}
public int Compare(T x, T y) {
Count++;
return x.CompareTo(y);
}
}
答案 1 :(得分:3)
您可以编写一个自定义IComparer<int>
来计算其使用次数,然后在搜索方法中使用它。 (或者我猜想,您可以使用自定义IEqualityComparer<int>
进行线性搜索。)
答案 2 :(得分:2)
您可以使用此扩展方法(基于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
}
}
答案 3 :(得分:0)
这是某种功课吗? List<T>.BinarySearch
方法不提供此类信息。
如果您想要比较次数,您必须编写自己的IComparer
二进制搜索,或者仍然使用.NET方法并根据列表的长度和元素的位置计算计数。 / p>