二分尋找

來源:互聯網
上載者:User

標籤:

演算法練習

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停止,所以注意
}

}

二分尋找

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.