標籤:
演算法練習
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停止,所以注意
}
}
二分尋找