二分查找算法,是基于有序的结果集进行查询的
二分查找的时间复杂度是O(logN)
写一段二分查询的代码:
public static void main(String[] args) {
int[] data = new int[]{1, 2, 3, 3, 5, 5, 6, 8, 9, 9, 10};
int queryData = 5;
int index = queryDataIndex(queryData, data);
System.out.println(index);
}
/**
* 查询指定 。。。
*
* @param queryData
* @param data
* @return -1 表示没有找到
*/
private static int queryDataIndex(int queryData, int[] data) {
if (data == null || data.length == 0) {
return -1;
}
int startIndex = 0, endIndex = data.length - 1;
int middleIndex = 0;
while (startIndex <= endIndex) {
middleIndex = startIndex + (endIndex - startIndex) / 2;
if (data[middleIndex] == queryData) {
return middleIndex;
}
if (data[middleIndex] > queryData) {
endIndex = middleIndex-1;
}
if (data[middleIndex] < queryData) {
startIndex = middleIndex+1;
}
}
return -1;
}
如果要求查找的时候返回重复元素的第一个,怎么办呢,通过二分查找,代码如下:
public static void main(String[] args) {
int[] data = new int[]{1, 2, 3, 3, 5, 5, 6, 8, 9, 9, 10};
int queryData = 10;
int index = queryDataIndex(queryData, data);
System.out.println(index);
}
/**
* 查询指定 。。。
*
* @param queryData
* @param data
* @return -1 表示没有找到
*/
private static int queryDataIndex(int queryData, int[] data) {
if (data == null || data.length == 0) {
return -1;
}
int startIndex = 0, endIndex = data.length - 1;
int middleIndex = 0;
int result = -1;
while (startIndex <= endIndex) {
middleIndex = startIndex + (endIndex - startIndex) / 2;
if (data[middleIndex] == queryData) {
result = middleIndex;
endIndex = middleIndex-1;
}
if (data[middleIndex] > queryData) {
endIndex = middleIndex-1;
}
if (data[middleIndex] < queryData) {
startIndex = middleIndex+1;
}
}
return result;
}