有没有办法计算二进制搜索中重复数字的索引值?

时间:2018-05-03 12:36:50

标签: c#

我希望能够计算已排序数组中的多个条目。在之前的尝试中,我尝试使用这样的列表。

public static List<int> duplicate = new List<int>();

但是,它不能正确计数并保持打印相同的索引号。在这一点上我非常难以接受任何帮助,我们将不胜感激。

class binarysearch
{
    public static int lowestIndex = 0;
    public static int highestIndex;
    public static int middleIndex = 0;
    public static int indexValue = -1;

    public static int binarySearch(double[] data, double target)
    {
        int highestIndex = data.Length - 1;

        while (lowestIndex < highestIndex)
        {
            middleIndex = lowestIndex + (highestIndex - lowestIndex) / 2;
            if (data[middleIndex] == target)
            {
                indexValue = middleIndex;
                highestIndex = middleIndex;
            }
            else if (data[middleIndex] > target)
            {
                highestIndex = middleIndex;
            }
            else
            {
                lowestIndex = middleIndex + 1;
            }   
        }

        return indexValue;
    }
}

编辑

public static List<int> duplicate = new List<int>();

的代码中提前声明
class dataset
{
   public static List<int> duplicate = new List<int>();
}

然后在主方法中打印

foreach (object dupes in dataset.duplicate)
{
 Console.WriteLine(dupes);
}

0 个答案:

没有答案