1、顺序查找
顺序查找,就是从第一个元素开始,按索引顺序遍历待查找序列,直到找出给定目标或者查找失败。
public class Test {
public static int seqSearch(int[] array, int target) {
for (int i = 0; i < array.length; i++) {
int p = array[i];
if (p == target) {
System.out.println("sucess to find out "+target+" from array, index="+i);
return i;
}
}
System.out.println("fail to find out the target");
return -1;
}
public static void main(String[] args) {
int[] data = { 3, 6, 7, 2, 12, 9, 0, 11 };
System.out.println(seqSearch(data, 12));
}
}
2、二分查找
二分查找一个顺序数组,假设数组是按升序排序,将表中间位置记录的关键字与查找的关键字比较,如果中间值大于查找值则往数组的左边继续查找,如果小于,则往数组的右边查找。
public class Test {
public static int seqSearch(int[] array, int target) {
int l = 0;
int h = array.length - 1;
while (l <= h) {
int mid = l + (h - l) / 2;
if (target < array[mid]) {
h = mid - 1;
} else if (target > array[mid]) {
l = mid + 1;
} else {
return mid;
}
}
return -1;
}
public static void main(String[] args) {
int[] data = { 10, 11, 12, 16, 18, 23, 29, 33, 48, 54, 57, 68, 77, 84, 98 };
System.out.println(seqSearch(data, 23));
}
}