二分查找又称折半查找,它是一种效率较高的查找方法。、
折半查找的算法思想:、将数列按有序化(递增或递减)排列,进行折半查找。可以明显减少比较次数,提高查找效率。
优点:查找比较次数少,查找速度快,性能好。
缺点:要求待查表为有序表,且插入删除困难。
public static void main(String[] args) {
int srcArray[] = {1, 3, 4, 5, 7, 8, 9, 10, 11, 17, 21, 23, 28, 30, 32, 38, 41, 47, 50, 56, 64, 78, 81, 88, 95, 98};
System.out.println("二分查找递归实现 " + searchValue(srcArray, 0, srcArray.length - 1, 47));
System.out.println("二分查找普通循环实现 " + searchValue(srcArray, 47));
}
//二分查找递归实现
public static int searchValue(int srcArray[], int start, int end, int key) {
int mId = (end - start) / 2 + start;
if (srcArray[mId] == key) {
return mId;
}
if (start >= end) {
return -1;
} else if (key > srcArray[mId]) {
return searchValue(srcArray, mId + 1, end, key);
} else if (start >= end) {
return searchValue(srcArray, start, mId - 1, key);
}
return 0;
}
//二分查找普通循环实现
public static int searchValue(int srcArray[], int key) {
int mId = srcArray.length / 2;
if (srcArray[mId] == key) {
return mId;
}
int start = 0;
int end = srcArray.length - 1;
while (start <= end) {
mId = (end - start) / 2 + start;
if (key < srcArray[mId]) {
end = mId - 1;
} else if (key > srcArray[mId]) {
start = mId + 1;
} else {
return mId;
}
}
return 0;
}