线性查找二维数组

1.算法描述

有序(行有序,列有序,且每行从左至右递增,列从上至下递增)二维数组查找,要求复杂度O(n)

 

2.使用到的相关知识:

结构体定义和使用,二维数组传递(http://blog.csdn.net/yzhhmhm/article/details/2045816

 

3.使用数组名传递

这个的不便之处很明显,一旦确定就是不能设置列值

//使用数组名实现(不便之处很明显:列值确定了,不能灵活)
loc* findValue(int a[][5], int row, int value){
	int col = sizeof(a)/sizeof(int)*row;
	cout<<"size:"<<col<<endl;
	//先按列比较(第0列),找到所在的行
	int currRow = 0;
	for(int i=0; i<row; i++){
		if(a[i][0] > value){
			if(i != 0) currRow = i - 1;
			break;
		}
	}

	int index = search(a[currRow], 5, value);
	//利用结构体指针
	loc *l;
	l->row = currRow;
	l->col = index;
	return l;
}

 

4.使用指针数组传递

//使用指针数组实现
loc findValue(int* a[], int row, int col, int value){
	//先按列比较(第0列),找到所在的行
	int currRow = 0;
	for(int i=0; i<row; i++){
		if(a[i][0] > value){
			if(i != 0) currRow = i - 1;
			break;
		}
	}

	int index = search(a[currRow], col, value);
	loc l;
	l.row = currRow;
	//在给定的行中搜索
	l.col = index;
	return l;
}

 

5.所有代码

/**
	*有序(行有序,列有序,且每行从左至右递增,列从上至下递增)二维数组查找
	*要求复杂度O(n)
	*/
#include <iostream>
using namespace std;
struct loc{
 int row;
 int col;
};

//如果找到放回下标,否则-1
int search(int *a, int length, int value){
	int i=0,j=length-1;
	while(i<=j){
		int center = (i+j)/2;
		if(a[center]<value) i=center+1;
		else if(a[center]>value) j=center-1;
		else return center;
	}
	return -1;
}


//使用数组名实现(不便之处很明显:列值确定了,不能灵活)
loc* findValue(int a[][5], int row, int value){
	int col = sizeof(a)/sizeof(int)*row;
	cout<<"size:"<<col<<endl;
	//先按列比较(第0列),找到所在的行
	int currRow = 0;
	for(int i=0; i<row; i++){
		if(a[i][0] > value){
			if(i != 0) currRow = i - 1;
			break;
		}
	}

	int index = search(a[currRow], 5, value);
	//利用结构体指针
	loc *l;
	l->row = currRow;
	l->col = index;
	return l;
}


//使用指针数组实现
loc findValue(int* a[], int row, int col, int value){
	//先按列比较(第0列),找到所在的行
	int currRow = 0;
	for(int i=0; i<row; i++){
		if(a[i][0] > value){
			if(i != 0) currRow = i - 1;
			break;
		}
	}

	int index = search(a[currRow], col, value);
	loc l;
	l.row = currRow;
	//在给定的行中搜索
	l.col = index;
	return l;
}

int main(){
	int a[5][5],k=0;
	for(int i=0; i<5;i++){
		for(int j=0; j<5; j++){
			a[i][j] = k++;
		}
	}
	
	int value;
	cout<<"输入要查找的值:";
	cin>>value;
	//---------1---------
	loc* ll = findValue(a, 5,value);
	if(ll->col != -1){
		cout<<"位置在:("<<ll->row<<","<<ll->col<<")"<<endl;
	}else{
		cout<<"没有找到!"<<endl;
	}
	
	//---------2---------
	//使用指针数组,必须先将二维数组转换为下面的形式
	int *p[] = {*a, *(a+1),*(a+2),*(a+3),*(a+4)};
	loc l = findValue(p, 5,5,value);
	if(l.col != -1){
		cout<<"位置在:("<<l.row<<","<<l.col<<")"<<endl;
	}else{
		cout<<"没有找到!"<<endl;
	}
	return 0;
}
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值