Java实现的常用的查找算法

时间:2021-02-22 10:59:04
public class Search {

/*
* 顺序查找,返回关键字在数组中第一次出现的位置, 没找到返回-1
*/

public static int searchSeq(int[] a, int key){

for(int i = 0; i < a.length; i++){
if (a[i] == key){
return i + 1;
}
}
return -1;
}

/*
* 折半查找,要求数组是有序排列的(从小到大)
* */


public static int searchBin(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+1;
}else if(a[mid] > key){ //如果中间值大于查找值,那么将高位标记减一
high = mid - 1;
}else{ //如果中间值小于查找值,将低位标记加一
low = low + 1;
}
}
return -1;
}

public static void main(String[] args) {
// int[] seq = {2, 4, 5, 6, 8, 10, 3};
// int[] bin = {1, 2, 3, 4, 5, 6, 7, 8};
// System.out.println(searchSeq(seq, 6));
// System.out.println(searchBin(bin, 8));

}

}