下面是我的通用二进制搜索.它适用于整数类型数组(它会找到其中的所有元素).但是当我使用字符串数组来查找任何字符串数据时会出现问题.它可以运行第一个索引和最后一个索引元素,但我找不到中间元素.
Stringarray = new string[] { "b", "a", "ab", "abc", "c" };
public static void BinarySearch<T>(T[] array, T searchFor, Comparer<T> comparer) {
int high, low, mid;
high = array.Length - 1;
low = 0;
if (array[0].Equals(searchFor))
Console.WriteLine("Value {0} Found At Index {1}",array[0],0);
else if (array[high].Equals(searchFor))
Console.WriteLine("Value {0} Found At Index {1}", array[high], high);
else
{
while (low <= high)
{
mid = (high + low) / 2;
if (comparer.Compare(array[mid], searchFor) == 0)
{
Console.WriteLine("Value {0} Found At Index {1}", array[mid], …Run Code Online (Sandbox Code Playgroud) 我正在尝试对具有 10 个数字的随机数组进行二分搜索。当我运行我的代码时,我输入的数字是随机数组中的一个数字,而不是只输出一次“找到它”,它会不断输出“找到”直到我关闭程序,但我不明白是什么我已经做了让它继续输出“找到它”。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Binary_Search
{
class Program
{
static void Main(string[] args)
{
int n = 10; //10 values in array
Random r = new Random();
int b; //value to search
int i; //loop control value
int[] a = new int[n + 1];
a[0] = 0; //starts at 0
for (i = 1; i <= n; i++) // set the array up
a[i] = a[i - 1] + r.Next(1, …Run Code Online (Sandbox Code Playgroud)