【问题标题】:linear/binary search functions not displaying anything?线性/二进制搜索功能不显示任何内容?
【发布时间】:2013-12-04 01:27:06
【问题描述】:

我正在比较线性搜索和二进制搜索以及它们的速度。但是当我编译程序时什么都没有显示,我不知道为什么。当我只输入它的线性搜索部分并对其进行测试时,这很有效。任何帮助将不胜感激~~。谢谢。

#include <iostream>
using namespace std;

int linearSearch(const int integerArray[],int,int);
int binarySearch(const int integerArray[],int,int);
const int SIZE = 20;

    int main()
    {
        int integerArray[SIZE]={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,10};
        int position1,position2;

        cout << "This program will compare search efficiency for the linear and binary searches " << endl;

        position1 = linearSearch(integerArray,SIZE,7);
        position2 = binarySearch(integerArray,SIZE,7);

        cout << position1 << endl;
        cout << position2 << endl;

        return 0;
    }

    int linearSearch(const int integerArray[],int SIZE,int value)
    {
        int index = 0;
        int position1 = -1;
        bool foundNum = false;

        while(index < SIZE)
        {
            if(integerArray[index] == value)
            {
                foundNum = true;
                position1 = index;
            }
            index++;
        }
        return position1;
    }

    int binarySearch(const int integerArray[],int size,int value)
    {
        int first = 0;
        int last = size-1;
        int midpoint = (first+last)/2;
        int position2 = -1;
        bool foundNum = false;

        while(!foundNum && first<=last)
        {
            if(integerArray[midpoint] == value)
            {
                foundNum = true;
                position2++;
                return position2;
            }
            else if(integerArray[midpoint] > value)
            {
                last = midpoint-1;
                position2++;
            }
            else
                last = midpoint+1;
                position2++;


        }
        return position2;
    }

【问题讨论】:

    标签: c++ function binary-search linear-search


    【解决方案1】:

    在您的 binarySearch 函数中,midpoint 永远不会更改,因此结果是无限循环,除非立即找到该数字。

    您应该通过将midpoint = (first+last)/2; 放在循环中来更新midpoint

    【讨论】:

      【解决方案2】:

      这听起来像是一个家庭作业问题,所以我不会为你做,但似乎问题出在你的二分搜索上。考虑这些项目:

      1. 每次迭代都需要重新计算中点。你只做一次。
      2. 需要有一种情况可以修改 first,以及您修改 last 的单独案例。你有 修改last的两种情况。
      3. 你还需要position2吗? midpoint 变量不是用于此目的吗?

      祝你好运!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-11-24
        • 1970-01-01
        • 1970-01-01
        • 2021-11-16
        • 1970-01-01
        • 1970-01-01
        • 2013-12-12
        • 2015-01-12
        相关资源
        最近更新 更多