c++ - 我的二进制搜索有问题吗?

标签 c++ search binary

这是我尝试实现一个二进制搜索方法以在 20 的数组中查找任意整数 X 并输出它在数组中出现的次数。

我的输出似乎是错误的,因为无论给定整数在数组中出现多少次,它都输出 1。

有人可以帮助我并告诉我我的代码有什么问题吗? (我知道 20 很小,线性方法更容易实现,但我使用 20 来简化事情)

只是为了确定,我输入的是 imin = 0 和 imax = 19 我还确保已对数组进行排序。

#include <iostream>
#include <cstdlib>
#include <vector>

using namespace std;
int A[20] = {0};
int x;
int imin;
int imax;

int BinarySearch(int A[], int value, int low, int high, int count) {
       if (high < low){          
           return -1; // not found
       } 
       int mid = low + ((high - low) / 2); 

       if (A[mid] > value){
       cout<< A[mid] << " > " << value <<endl; 
           return BinarySearch(A, value, low, mid-1, count);
       }
       else if (A[mid] < value){
      cout<< A[mid] << " < " << value <<endl; 
           return BinarySearch(A, value, mid+1, high, count);
       }
       if (A[mid] == value){
       cout<< A[mid] << " = " << value <<endl; 
       count = count + 1;
       }

      return count;

   }

int main(){


    cout<<"Enter 20 integers"<<endl;

    for (int i = 0; i < 20;i++){
    cin>>A[i];
    }


    cout<<"Enter the integer x"<<endl;
    cin>>x;

    cout<<"What is imin?"<<endl;
    cin>>imin;

    cout<<"What is imax?"<<endl;
    cin>>imax;


int temp;
int i;    

for (int j = 1; j < 20; j++){
    i = j - 1;        
    temp = A[j]; 

    while ((i>=0) && (A[i] > temp) ) 
    {  
       A[i+1] = A[i];
       i=i-1;                                                  
    }


    A[i+1] = temp; 


 }


 int count = BinarySearch(A, x, imin, imax, 0);

cout<<count<<endl;

     system("pause");

}

非常感谢

编辑:添加了一些更正。但是我想二进制搜索算法似乎有问题!

最佳答案

int A[] = {0}; 更改为

int* A=new int[20]; 

int A[20]={0} 目前您不是为 20 个整数分配内存,而是为 1 个整数分配内存。

同时更改您的 ifs 以涵盖 {}

中的指令组
if(){
    //... many instructions
}else{
    //... many instructions
}

关于c++ - 我的二进制搜索有问题吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15885752/

相关文章:

c++ - 当我更改着色器中与这些制服无关的一行代码时,向着色器 (GLSL) 发送数据失败

c++ - 使用 C++ MFC,获取添加到浏览器(Chrome、IE 或 Firefox)的扩展列表

sql - 使用 MySQL 搜索多个表

javascript - 在 Node Red 中将 Int 数转换为 Binary

javascript - 我可以在 Node Webkit 中保护 javascript 以外的资源吗?

python - Python中数值的陷阱, "How deep?"

C++:关于重载 operator new 的一般想法

c++ - 我正在制作这个程序,服务器不会发送给客户端

exception - Elasticsearch 查询 "empty index"

php - 搜索特定关键字 MySQL