二分查找

算法练习

package common;

import java.util.Arrays;

public class bs {

void nbs(int n,int s[],int x)
{
int low=0;
int high=n-1;
while(low<=high)
{
int mid=(low+high)/2;
if(x==s[mid])
{
System.out.print("p:"+mid);
System.exit(0);
}
else if(x>s[mid])
{
low=mid+1;
}
else
{
high=mid-1;
}

}
System.out.print("have no the"+x);
System.exit(1);//非正常退出
}

void dbs(int s[],int low,int high,int x)
{
if(low>high)
{
System.out.print("have no the"+x);
System.exit(1);
}
int mid=(low+high)/2;
if(x==s[mid])
{
System.out.print("p:"+mid);
System.exit(0);//正常退出
}
else if(x>s[mid])
{
dbs(s,mid+1,high,x);
}
else
{
dbs(s,low,mid-1,x);
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
bs a=new bs();
int s[]={1,7,9,90,888,98,78,880};
Arrays.sort(s);

for(int i:s)
{System.out.println(i);}


System.out.println("非递归二分查找:");
a.nbs(s.length, s, 1);
//********************************************************************
System.out.println("递归二分查找:");
a.dbs(s, 0, s.length-1, 90);
//********************************************************************
//[猪]^(* ̄(oo) ̄)^ :由于上述二分查找均为无返回值,所以结束采用exit函数,
//因此导致nbs与dbs无法同时出结果(按顺序的话),因为exit表示jvm停止,所以注意
}

}

原文地址:https://www.cnblogs.com/8335IT/p/4780753.html