我正在尝试对二维数组进行二进制搜索,这将为我提供数组中每个键的位置,我的代码是
#include <iostream>
#include <vector>
using namespace std;
vector<pair<int,int> > up;
vector<pair<int,int> > down;
void binsearchd(int **A,int row,int low,int high,int key)
{
int mid=(low+high)/2;
if(low==high&&A[row][mid]!=key)//!(A[row][mid]<=key&&A[row][mid-1]<=key&&A[row-1][mid] <=key&&A[row+1][mid]>key&&A[row][mid+1]>key))
return;
if(A[row][mid]==key)//<=key&&A[row][mid-1]<=key&&A[row-1][mid]<=key&&A[row+1][mid]>key&&A[row][mid+1]>key)
{
down.push_back({row,mid});
return;
}
if(A[row][mid]>key)
binsearchd(A,row,low,mid,key);
else if(A[row][mid]<key)
binsearchd(A,row,mid+1,high,key);
else
{
binsearchd(A,row,low,mid,key);
binsearchd(A,row,mid+1,high,key);
}
return;
}
void searchd(int **A,int lowi,int lowj,int highi,int highj,int key)
{
if(lowi==highi)
{
binsearchd(A,lowi,lowj,highj,key);
return;
}
int midi=(lowi+highi)/2,midj=(lowj+highj)/2;
if(A[midi][midj]==key)//<=key&&A[midi][midj-1]<=key&&A[midi-1][midj]<=key&&A[midi+1][midj]>key&&A[midi][midj+1]>key)
down.push_back({midi,midj});
if(A[midi][midj]>key)
{
searchd(A,lowi,lowj,midi,highj,key);
searchd(A,midi+1,lowj,highi,midj,key);
}
else if(A[midi][midj]<key)
{
searchd(A,midi+1,lowj,highi,highj,key);
searchd(A,lowi,midj+1,midi+1,highj,key);
}
else
{
searchd(A,lowi,lowj,midi,highj,key);
searchd(A,midi+1,lowj,highi,highj,key);
binsearchd(A,midi,lowj,highj,key);
}
return;
}
int main()
{
int row,col;
while(cin>>row>>col&&row){
int **A=new int*[row];
for(int i=0;i<row;++i)
{
A[i]=new int[col];
for(int j=0;j<col;++j)
cin>>A[i][j];
}
int query;
cin>>query;
while(query--)
{
int d;
cin>>d;
//searchu(A,1,1,row+1,col+1,u);
searchd(A,0,0,row,col,d);
int max=-999999999;
//for(vector<pair<int,int> >::iterator itr=up.begin();itr!=up.end();++itr)
//{
for(vector<pair<int,int> >::iterator itr2=down.begin();itr2!=down.end();++itr2)
{
cout<<itr2->first<<" "<<itr2->second<<endl;
}
up.resize(0);
down.resize(0);
}
for(int i=0;i<row+1;++i)
delete A[i];
delete A;
}
}
问题是它在数组上给出了分段错误
4 4 4 4
4 4 4 4
4 4 4 4
4 4 4 4
key=4 并且在大多数情况下,我尝试调试发现 seg 错误的原因是二进制搜索第 4 行,它大于第 4 行。行..但我无法找出该行是如何出现的,因为我的代码每次将行分成两半,这就是它应该如何越过边界..有什么提示吗?