- 非递归方法
public static int select(int[] arry,int num){
int high=arry.length-1;
int low=0;
while(low<=high){
//这种方式取中间值是为了防止溢出
int mid=low+(high-low)/2;
if(num<arry[mid]){
high=mid-1;
}
else if(num>arry[mid]){
low=mid+1;
}
else if(num==arry[mid]){
return mid;
}
}
return -1;
}
2 . 递归方法
public static int select1(int [] arry,int low,int high,int num){
int mid=low+(high-low)/2;
while(low<=high){
if(num==arry[mid]){
return mid;
}
else if(num>arry[mid]){
return select1(arry,mid+1,high,num);
}
else if(num<arry[mid]){
return select1(arry,low,mid-1,num);
}
}
return -1;
}
本文介绍了两种数组查找的方法:非递归方法与递归方法。非递归方法通过迭代的方式逐步缩小搜索范围,直至找到目标元素或确定不存在。递归方法则采用分治策略,将问题分解为子问题来寻找目标元素的位置。
2230

被折叠的 条评论
为什么被折叠?



