public class sequenceQuery {
/* 对于无序表的搜索 顺序搜索*/
public int seqSearch(int[] datalist, int target) {
for (int i = 0; i < datalist.length; i++) {
if (datalist[i] == target)
return i;
}
return -1;
}
/* 二叉搜索,对于有序表 */
public int binarySearch(int[] datalist, int target) {
int mid = 0;
int first = 0;
int last = datalist.length - 1;
while (first <= last) {
mid = (first + last) / 2;
if (target == datalist[mid])
return mid;
else {
if (target > datalist[mid])
first = mid + 1;
else
last = mid - 1;
}
}
return -1;
}
public static void main(String[] args) {
int datalist1[] = { 23, 566, 89, 0, 2, 7, 90, 34, 12, 744, 3257 };
int datalist2[] = { 23, 28, 89, 100, 200, 778, 902, 1234, 1724, 7442,32257 };
sequenceQuery s = new sequenceQuery();
System.out.println(s.seqSearch(datalist1, 90));
System.out.println(s.binarySearch(datalist2, 902));
}
}