一个二维数组,没每一行都按照从左到右递增的顺序排序,每一个列都按照从上到下递增的排序,设计一个函数,输入一个这样的数组和一个整数,判断数组中是否含有该整数。
例如下面数组,查找数字7返回true,查找5,返回false
1,2,8,9
2,4,9,12
4,7,10,13
6,8,11,15
一种思路,先查找第一行,使用二分查找判断是否存在,如果存在则通过参数found返回true,如果不存在,返回行里最大小于查找数的列号,如查找的是7,第一行不存在,那么返回2所在的下标。之后根据列号查找,如果存在则返回true,不存在则返回false,end。
#include <iostream>
using namespace std;
//先找列
int FindColumn(int matrix[][4],int row,int& columns,int& number,bool& found){
int column=-1;
if(matrix!=nullptr && row>=0 && columns>0){
int start=0;
int end=columns-1;
bool upOrdown=false;
if(matrix[row][start]==number){
found=true;
column=0;
return column;
}
else if(matrix[row][start]>number){
return column;
}
column=0;
while(start<=end){
int mid=(start+end)/2;
if(matrix[row][mid]==number){
found=true;
column=end;
return column;
}
else if(matrix[row][mid]>number){
end=mid-1;
column=mid-1;
}
else if(matrix[row][mid]<number){
start=mid+1;
column=mid;
}
}
}
return column;
}
//后找行
int FindRow(int matrix[][4],int& rows,int column,int& number,bool& found){
int row=-1;
if(matrix!=nullptr && column>=0 && rows>0){
int start=0;
int end=rows-1;
bool upOrdown=false;
if(matrix[end][column]==number){
found=true;
column=end;
return row;
}
else if(matrix[end][column]<number){
return row;
}
end-=1;
while(start<=end){
int mid=(start+end)/2;
if(matrix[mid][column]==number){
found=true;
row=end;
return row;
}
else if(matrix[mid][column]>number){
end=mid-1;
row=mid-1;
}
else if(matrix[mid][column]<number){
start=mid+1;
row=mid;
}
}
}
return row;
}
bool Find(int matrix[][4],int rows,int columns,int number){
bool found=false;
int column=FindColumn(matrix,0,columns,number,found);
if(found==true)
return found;
FindRow(matrix,rows,column,number,found);
return found;
}
int main(){
int matrix[4][4]={{1,2,8,9},{2,3,9,12},{4,7,10,13},{6,8,11,15}};
bool found_5=Find(matrix,4,4,5);
cout<<"found_5="<<found_5<<endl;
bool found_7=Find(matrix,4,4,7);
cout<<"found_7="<<found_7<<endl;
return 0;
};