JAVA二分查找
答案:2 悬赏:0
解决时间 2021-02-19 07:41
- 提问者网友:喵星人荷西
- 2021-02-18 08:15
请高手写个 JAVA二分查找 ~请指教~
最佳答案
- 二级知识专家网友:留下所有热言
- 2021-02-18 09:01
public class test {
static int bsearch( int[] a, int v ) {
int l, r;
l = 0; r = a.length-1;
while ( l <= r ) {
int m = (l+r)/2;
if ( a[m] == v ) return m; else
if ( a[m] > v ) r = m-1; else
if ( a[m] < v ) l = m+1;
}
return -1;
}
public static void main( String[] args ) {
int[] a = { 1,3,5,7,9 };
for ( int i = 0; i < 10; ++i )
System.out.println( "find " + i + " at pos: " + bsearch( a, i ) );
}
}
static int bsearch( int[] a, int v ) {
int l, r;
l = 0; r = a.length-1;
while ( l <= r ) {
int m = (l+r)/2;
if ( a[m] == v ) return m; else
if ( a[m] > v ) r = m-1; else
if ( a[m] < v ) l = m+1;
}
return -1;
}
public static void main( String[] args ) {
int[] a = { 1,3,5,7,9 };
for ( int i = 0; i < 10; ++i )
System.out.println( "find " + i + " at pos: " + bsearch( a, i ) );
}
}
全部回答
- 1楼网友:我叫很个性
- 2021-02-18 10:06
以下代码是关于对象的 二分查找 的例子,已经测试通过,执行即可。 student 是基本比较对象类 dichotomy 是二分法执行类 test 是测试类 package com.dichotomy; public class student implements comparable { private int id; private string name; private string idcard; private string sex; private string mobile; public int getid() { return id; } public void setid(int id) { this.id = id; } public string getname() { return name; } public void setname(string name) { this.name = name; } public string getidcard() { return idcard; } public void setidcard(string idcard) { this.idcard = idcard; } public string getsex() { return sex; } public void setsex(string sex) { this.sex = sex; } public string getmobile() { return mobile; } public void setmobile(string mobile) { this.mobile = mobile; } public int compareto(student o) { //不同的执行次序决定排序和查找次序不同,可以同下面的调换一下 if(this.getid() < o.getid()){ return -1; } else if(this.getid() == o.getid()){ ; } else { return 1; } //不同的执行次序决定排序和查找次序不同 int c = this.getidcard().compareto(o.getidcard()); if(c != 0){ return c; } //不同的执行次序决定排序和查找次序不同 int n = this.getname().compareto(o.getname()); if(n != 0){ return n; } return 0; } public string tostring(){ stringbuffer sb = new stringbuffer(); sb.append(this.getid()).append("\t"); sb.append(this.getname()).append("\t"); sb.append(this.getidcard()).append("\t"); sb.append(this.getmobile()).append("\t"); sb.append(this.getsex()); return sb.tostring(); } }
我要举报
如以上问答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
大家都在看
推荐资讯