二分查找的递归函数

发布于 2024-08-29 01:20:30 字数 884 浏览 6 评论 0原文

创建用于二分搜索的递归函数。
此函数接受一个排序数组和一个要搜索的项目,并返回该项目的索引(如果项目在数组中),或者返回 -1(如果项目不在数组中)。
此外,编写一个测试程序来测试你的功能。

template <class elemType>
int orderedArrayListType<elemType>::binarysearch
                                (const elemType& item) const
{
    int first= 0;
    int last = length -1;
    int mid;
    int list[];
    int BinarySearch(,Type & Item, int first, int last)
    bool found = false;
    while (first <= last && !found){
        mid = (first + last) / 2;
        if (list[mid] > item)
            return BinarySearch(list, item, first, mid -1)
        found = true;
        else if (list[mid] > item)
            return BinarySearch( list, item, first, mid -1)
            last = mid - 1;
        else 
            first = mid + 1;
    }
    if (found)
        return mid;
    else 
        return -1;
}

Create a recursive function for the binary search.
This function accepts a sorted array and an item to search for, and returns the index of the item (if item is in the array), or returns -1 (if item is not in the array).
Moreover, write a test program to test your function.

template <class elemType>
int orderedArrayListType<elemType>::binarysearch
                                (const elemType& item) const
{
    int first= 0;
    int last = length -1;
    int mid;
    int list[];
    int BinarySearch(,Type & Item, int first, int last)
    bool found = false;
    while (first <= last && !found){
        mid = (first + last) / 2;
        if (list[mid] > item)
            return BinarySearch(list, item, first, mid -1)
        found = true;
        else if (list[mid] > item)
            return BinarySearch( list, item, first, mid -1)
            last = mid - 1;
        else 
            first = mid + 1;
    }
    if (found)
        return mid;
    else 
        return -1;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

树深时见影 2024-09-05 01:20:30

在美国有一种儿童游戏,一个孩子选择 1 到 10 之间的一个数字,另一个孩子必须猜出这个数字。如果他们猜错了,第一个孩子就会说“更高”或“更低”。

大多数孩子一开始都是随机猜测,平均需要尝试 4-5 次才能成功。我意识到(这可能就是我最终选择计算机科学的原因),最好的办法是选择中间点(5.5,所以选择 5 或 6。我会选择 5。)。根据他们的说法(“更高”或“更低”),选择一个新范围:1-4 或 6-10。选择该范围中间的数字(2 或 8)。继续将范围分成两半,直到得到数字。

这是对排序数组的二分查找(排序数组是从 1 到 10 的数字)。

要在代码中实现这一点,只需继续执行上述相同的过程即可。选择范围的中点,并根据答案创建一个新范围。

这是一个Java 中的解决方案 递归地执行此操作:

public class BinarySearchRecursive
{
    public static final int NOT_FOUND = -1;

    /**
     * Performs the standard binary search
     * using two comparisons per level.
     * This is a driver that calls the recursive method.
     * @return index where item is found or NOT_FOUND if not found.
     */
    public static int binarySearch( Comparable [ ] a, Comparable x )
    {
        return binarySearch( a, x, 0, a.length -1 );
    }

    /**
     * Hidden recursive routine.
     */
    private static int binarySearch( Comparable [ ] a, Comparable x,
                                     int low, int high )
    {
        if( low > high )
            return NOT_FOUND;

        int mid = ( low + high ) / 2;

        if( a[ mid ].compareTo( x ) < 0 )
            return binarySearch( a, x, mid + 1, high );
        else if( a[ mid ].compareTo( x ) > 0 )
            return binarySearch( a, x, low, mid - 1 );
        else
            return mid;
    }

    // Test program
    public static void main( String [ ] args )
    {
        int SIZE = 8;
        Comparable [ ] a = new Integer [ SIZE ];


    for( int i = 0; i < SIZE; i++ )
        a[ i ] = new Integer( i * 2 );

    for( int i = 0; i < SIZE * 2; i++ )
        System.out.println( "Found " + i + " at " +
                                 binarySearch( a, new Integer( i ) ) );
    }
}

There's a child's game in the USA where one child picks a number between 1 and 10, and the other child has to guess that number. If they guess wrong, the first child says "higher" or "lower".

Most kids start out guessing randomly, and will take about 4-5 tries on average to succeed. I realized (and this is probably why I ended up in computer science), that the best thing to do is pick the mid point (5.5, so pick either 5 or 6. I'll go with 5.). Based on what they say ("higher" or "lower"), select a new range, either 1-4 or 6-10. Pick the number in the middle of that range (2 or 8). Keep splitting the range in half until you get the number.

That's a binary search on a sorted array (the sorted array being numbers from 1 to 10).

To implement that in code, just keep doing the same process described above. Pick the midpoint of the range, and create a new range based on the answer.

Here's one solution in Java that does this recurvively:

public class BinarySearchRecursive
{
    public static final int NOT_FOUND = -1;

    /**
     * Performs the standard binary search
     * using two comparisons per level.
     * This is a driver that calls the recursive method.
     * @return index where item is found or NOT_FOUND if not found.
     */
    public static int binarySearch( Comparable [ ] a, Comparable x )
    {
        return binarySearch( a, x, 0, a.length -1 );
    }

    /**
     * Hidden recursive routine.
     */
    private static int binarySearch( Comparable [ ] a, Comparable x,
                                     int low, int high )
    {
        if( low > high )
            return NOT_FOUND;

        int mid = ( low + high ) / 2;

        if( a[ mid ].compareTo( x ) < 0 )
            return binarySearch( a, x, mid + 1, high );
        else if( a[ mid ].compareTo( x ) > 0 )
            return binarySearch( a, x, low, mid - 1 );
        else
            return mid;
    }

    // Test program
    public static void main( String [ ] args )
    {
        int SIZE = 8;
        Comparable [ ] a = new Integer [ SIZE ];


    for( int i = 0; i < SIZE; i++ )
        a[ i ] = new Integer( i * 2 );

    for( int i = 0; i < SIZE * 2; i++ )
        System.out.println( "Found " + i + " at " +
                                 binarySearch( a, new Integer( i ) ) );
    }
}
坏尐絯 2024-09-05 01:20:30

您还可以google“递归二分搜索”和

编辑-维基百科知道一切(特别是当涉及到cs时):

最直接的
[二分搜索算法]的实现是递归的,其中
递归搜索子范围
由比较决定:

   BinarySearch(A[0..N-1], value, low, high) {
       if (high < low)
           return -1 // not found
       mid = low + ((high - low) / 2) 
       if (A[mid] > value)
           return BinarySearch(A, value, low, mid-1)
       else if (A[mid] < value)
           return BinarySearch(A, value, mid+1, high)
       else
           return mid // found
   }

You could also google "recursive binary search" and voila!

EDIT- Wikipedia knows all (especially when it comes to cs):

The most straightforward
implementation [of the binary search algorithm] is recursive, which
recursively searches the subrange
dictated by the comparison:

   BinarySearch(A[0..N-1], value, low, high) {
       if (high < low)
           return -1 // not found
       mid = low + ((high - low) / 2) 
       if (A[mid] > value)
           return BinarySearch(A, value, low, mid-1)
       else if (A[mid] < value)
           return BinarySearch(A, value, mid+1, high)
       else
           return mid // found
   }
幻想少年梦 2024-09-05 01:20:30

只需使用 std::binary_search 即可。告诉导师,函数实际上是在 your_favorite_compiler 中递归实现的。

Just use std::binary_search. Tell the tutor that function is actually implemented recursively in your_favorite_compiler.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文