------------------------------->>>>>>>>>>>>>>>>>>>>
import java.util.Scanner;
public class LinearSearch {
/**
* 2010 /04 /29
*
* @线性查找
* @author panguiming
*/
public static boolean LSearch(int a[], int key) {
for (int i = 0; i < a.length; i++) {
if (key == a[i]) {
// key在数组中的下标
System.out.println(key + "位置:" + i);
return true;
}
}
System.out.println(key + " 在数组中不存在!");
return false;
}
public static void main(String[] args) {
System.out.println("------->>>>>请你输入你所要查找的数据:");
int a[] = { 3, 5, 4, 8, 6 };
Scanner sc = new Scanner(System.in);
int key = sc.nextInt();
LinearSearch.LSearch(a, key);
}
}
--------------------------------------->>>>>>>>>>>>>>>>>>>>>>>
import java.util.Scanner;
public class BirnarySearch {
/**
* 2010 /04 /29
*
* @折半查找
* @author panguiming
*/
public boolean bSearch(int a[], int key) {
int left = 0;
int right = a.length - 1;
int middle;
while (left <= right) {
middle = (left + right) / 2;
if (key > a[middle]) {
left = middle + 1;
} else if (key < a[middle]) {
right = middle - 1;
} else if (key == a[middle]) {
// key在数组中的下标
System.out.println(key + " 在数组中的位置: " + middle);
return true;
}
}
System.out.println(key + " 在数组中不存在!");
return false;
}
public static void main(String[] args) {
System.out.println("------->>>>>请你输入你所要查找的数据:");
Scanner sc = new Scanner(System.in);
int key = sc.nextInt();
int a[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
BirnarySearch bs = new BirnarySearch();
bs.bSearch(a, key);
}
}