2013-04-28 90 views
-2

无论我搜索什么值,程序都会在文件中找不到它。我无法弄清楚我的代码有什么问题。二进制搜索功能故障

 int main() 
    { 
     int array1[MAX_NUMBER]; 
     int length; 
     int number; 
     int location; 

     input (array1, MAX_NUMBER, length); 

     cout<<"Please enter a number to search for:"<<endl; 
     cin>>number; 

     location=search(array1, length, number); 

     if (location!=-1) 
     { 
      cout<<"The number "<<number<<" was found in the "<<location<<" position."<<endl; 
     } 

     else 
     { 
      cout<<"The number "<<number<<" was not found in the file."<<endl; 
     } 




     return 0; 
    } 

void input(int a[], int size, int& number_used) 
{ 
    ifstream infile; 
    int input; 

    infile.open("numbers.txt"); 

    if (infile.fail()) 
    { 
     cout<<"Input file opening failed."<<endl; 
     exit(1); 
    } 

    int i; 


    for (i=0; i<=size; i++) 
    { 
     while (infile>>input) 
     { 

      a[i]=input; 
      cout<<a[i]<<endl; 

     } 
    } 

    number_used=i; 

} 

int search(const int a[], int number_used, int search_value) 
{ 
    int start=1; 
    int end=number_used; 
    int key=search_value; 

    while (start<=end) 
    { 
     int mid=((start+end)/2); 

     if (a[mid]==key) 
     { 
      return mid; 
     } 

     if (a[mid]>key) 
     { 
      end=mid-1; 
     } 

     else 
     { 
      start=mid+1; 
     } 

    } 
     return -1; 


} 

我的问题在主代码或搜索功能?

输入文件:

1 
5 
6 
7 
11 
19 
21 
23 
33 
54 
78 
97 

例如,键入19,则输出为 “数19在该文件中未找到”。

+2

您的问题是,您没有使用调试器 – 2013-04-28 16:56:49

回答

0

二进制搜索要求数组已经排序。手工尝试你的算法:在[4,1,3,6,5]中找到数字4。 4大于中间元素,所以算法将转到数组的[4,6,5]部分。

+0

虽然数组已被排序。另外,你的例子有点奇怪。 – Xymostech 2013-04-28 16:50:26

1

您不计算正确读入的值列表的长度。你在一个循环内部有一个循环,它做了一些奇怪的事情。

,你应该做的是什么更多的东西一样:

int i; 

while (i < size && infile >> input) 
{ 
    a[i]=input; 
    cout<<a[i]<<endl; 
    i++; 
} 

number_used=i; 
+0

这个修好了!谢谢 – iamthewalrus 2013-04-28 17:04:59

+0

@iamthewalrus现在尝试搜索值“1”。 – WhozCraig 2013-04-28 17:05:34

2

你不填充阵列正确的功能input。 您必须使用另一个索引存储值数组,否则i不会显示在a有效和有意义的指标:

int k = 0; // <-------------------------- 

int i; 
for (i = 0; i <= size; i++) 
{ 
    while (infile >> input && k < size) 
    { 

     a[k] = input; // <---------------- 

     k++; // <---------------- 
    } 
} 

number_used = k; // <------------- 

而且,作为WhozCraig评论说,你应该知道数组开始从01因此search方法:

int start = 0; 
+0

+1,如果搜索到,搜索功能将永远不会在[0]槽中找到值。这段代码有几个错误,初始化是最明显的。有人需要对基于0的索引进行复习。 (以及线路调试器业务端的时间)。 – WhozCraig 2013-04-28 17:04:08

+0

如果'k'变得大于'size',这个代码仍然可以将更多的值放入'a'中。你总是使用'k'来索引,但你只能在'i'上进行大小检查。 – Xymostech 2013-04-28 17:54:47