1
public int BinarySearch(int x)
{
    //if (Attendees.Length == 0)
    //    return -1;
    int mid =  (Count/ 2) -1;
    Student cur = new Student(x);

    while (cur.CompareTo(Attendees[mid]) != 0)
    {
        int sCount = Count;
        if (cur.CompareTo(Attendees[mid]) < 0)
        {
            int NCount = sCount / 2;
            mid = NCount / 2 - 1;    
        }
        if (cur.CompareTo(Attendees[mid]) > 0)
        {
            int Start = mid +1;
            mid = (Start + sCount) / 2;
        }
        else
            break;

        cur = Attendees[mid];                
    }
    if (cur.CompareTo(Attendees[x]) == 0)
        return mid;
    else 
        return -1;
}

谁能帮我找出为什么我的二进制搜索不起作用?我对编程很陌生,所以任何帮助都将不胜感激。谢谢你。

4

1 回答 1

3

我认为您并没有真正掌握二进制搜索的含义。x在您的代码中,您正在搜索数组中的哪个位置元素- 你猜怎么着?就位了x

二分查找的意义在于找出一个元素的索引。Soooo 你需要搜索一个给定的Student

public int BinarySearch(Student student)
{
    // Search the entire range
    int min = 0;
    int max = Attendees.Length;
    int mid = 0;

    do
    {
        // Find the pivot element
        mid = min + ((max - min) / 2);

        // Compare
        int comparison = student.CompareTo(Attendees[mid]);
        if (comparison < 0)
        {
            max = mid;
        }
        if (comparison > 0)
        {
            min = mid;
        }
    }
    while (min < max && comparison != 0);

    if (comparison != 0)
        return -1;
    return mid;
}

这段代码可能无法 100% 工作,因为我还没有尝试过并将它写在我的脑海中,但它会为你指明正确的方向。现在,在此代码上使用调试器并单步执行它以查看它是否按预期工作。

于 2013-02-07T09:16:14.567 回答