二分查找
- 1、顺序存储结构
- 2、元素有序
二分查找非递归-Java 实现
//二分查找非递归实现
public class BinarySearch {
public static int BinSearch(int a[],int key){
int n = a.length;
int low=0,high=n-1,mid;
while(low<=high){
mid = (low+high)/2;
if(key==a[mid]){
return mid; //查找成功,返回key所在下标
}else if(key<a[mid]){
high = mid -1;
}else{
low = mid + 1;
}
}
return -1; //查找失败
}
public static void main(String[] args) {
int a[]={2,4,7,18,25,34,56,68,89};
int key = 68;
int index = BinarySearch.BinSearch(a, key);
System.out.println("要查找元素的下标为(如下标为-1,则查找失败):"+index);
}
}
二分查找非递归-C++ 实现
//二分查找非递归算法
#include <iostream>
using namespace std;
//二分查找算法
int BinarySearch(int a[],int key,int low,int high){
int mid;
while(low<=high){
mid = (low+high)/2;
if(key==a[mid]){
return mid;
}else if(key<a[mid]){
high = mid - 1;
}else{
low = mid + 1;
}
}
return -1;
}
int main()
{
int a[]={2,4,7,18,25,34,56,68,89};
int key = 68;
int n = (sizeof(a) / sizeof(a[0]));
int index = BinarySearch(a,key,0,n-1);
cout<<"有序数组为:"<<endl;
for(int i=0;i<n;i++){
cout<<a[i]<<" ";
}
cout<<"
要查找的元素key为:"<<key<<endl;
cout<<"要查找元素的下标为:"<<index<<endl;
return 0;
}