java查找算法
程序员文章站
2024-03-01 09:10:46
...
顺序查找算法
public static int search (int a[],int k){
int high = 1;
for(int i = 0;i<a.length;i++) {
if(a[i] != k) {
high = high+1;
}else {
return high;
}
}
return high;
}
折半算法
public static int zhebansearch (int a[],int k) {
int high = a.length;
int low = 0;
int middel = (high + low)/2;
while(low<high) {
if(a[middel]<k) {
low = middel;
middel = (high + low)/2;
continue;
}else
if(a[middel]>k){
high = middel;
middel = (high + low)/2;
continue;
}
if(a[middel] == k) {
break;
}
}
return middel+1;
}
public static void main(String[] args) {
// TODO 自動生成されたメソッド・スタブ
int a[]= {1,3,7,5,8,2};
int k = 2;
int result = search(a,k);
System.out.println(result);
}
}