0

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

#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;
    }
4

2 回答 2

0

在你的binarySearch函数midpoint中永远不会改变,所以结果是一个无限循环,除非立即找到数字。

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

于 2013-12-04T01:34:08.167 回答
0

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

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

祝你好运!

于 2013-12-04T01:34:50.260 回答