/**
* 有序表的查找
* @author neu_fufengrui@163.com
*
*/
public class Search {
/**
* 顺序查找
*/
public static int exec(int a[], int key){
for(int i = 0; i < a.length; i++){
if(a[i] == key){
return i;
}
}
return -1;
}
/**
* 顺序表二分查找
*/
public static int exec2(int a[], int key){
int low = 0, high = a.length - 1;
while(low <= high){
int mid = (low + high) / 2;
if(a[mid] == key){
return mid;
}else if(a[mid] > key){
high = mid - 1;
}else if(a[mid] < key){
low = mid + 1;
}
}
return -1;
}
public static void main(String[] args) {
int a[] = {05, 13, 19, 21, 37, 56, 64, 75, 80, 88, 92};
System.out.println(Search.exec(a, 37));
System.out.println(Search.exec(a, 63));
System.out.println(Search.exec2(a, 37));
System.out.println(Search.exec2(a, 63));
}
}
数据结构--顺序查找、二分查找
最新推荐文章于 2024-09-22 11:41:42 发布