1、前提:二分查找的前提是需要查找的数组必须是已排序的,我们这里的实现默认为升序
2、原理:将数组分为三部分,依次是中值(所谓的中值就是数组中间位置的那个值)前,中值,中值后;将要查找的值和数组的中值进行比较,若小于中值则在中值前面找,若大于中值则在中值后面找,等于中值时直接返回。然后依次是一个递归过程,将前半部分或者后半部分继续分解为三部分。可能描述得不是很清楚,若是不理解可以去网上找。从描述上就可以看出这个算法适合用递归来实现,可以用递归的都可以用循环来实现。所以我们的实现分为递归和循环两种,可以根据代码来理解算法
3、实现:代码如下
-
package org.cyxl.algorithm.search;
-
-
-
-
-
-
-
public class BinarySearch {
-
private int rCount=0;
-
private int lCount=0;
-
-
-
-
-
-
public int getrCount() {
-
return rCount;
-
}
-
-
-
-
-
-
public int getlCount() {
-
return lCount;
-
}
-
-
-
-
-
-
-
-
-
-
public int searchRecursive(int[] sortedData,int start,int end,int findValue)
-
{
-
rCount++;
-
if(start<=end)
-
{
-
-
int middle=(start+end)>>1;
-
-
int middleValue=sortedData[middle];
-
-
if(findValue==middleValue)
-
{
-
-
return middle;
-
}
-
else if(findValue<middleValue)
-
{
-
-
return searchRecursive(sortedData,start,middle-1,findValue);
-
}
-
else
-
{
-
-
return searchRecursive(sortedData,middle+1,end,findValue);
-
}
-
}
-
else
-
{
-
-
return -1;
-
}
-
}
-
-
-
-
-
-
-
-
public int searchLoop(int[] sortedData,int findValue)
-
{
-
int start=0;
-
int end=sortedData.length-1;
-
-
while(start<=end)
-
{
-
lCount++;
-
-
int middle=(start+end)>>1;
-
-
int middleValue=sortedData[middle];
-
-
if(findValue==middleValue)
-
{
-
-
return middle;
-
}
-
else if(findValue<middleValue)
-
{
-
-
end=middle-1;
-
}
-
else
-
{
-
-
start=middle+1;
-
}
-
}
-
-
return -1;
-
}
-
}
4、测试代码
-
package org.cyxl.algorithm.search.test;
-
-
import org.cyxl.algorithm.search.BinarySearch;
-
import org.junit.Test;
-
-
-
public class BinarySearchTest {
-
@Test
-
public void testSearch()
-
{
-
BinarySearch bs=new BinarySearch();
-
-
int[] sortedData={1,2,3,4,5,6,6,7,8,8,9,10};
-
int findValue=9;
-
int length=sortedData.length;
-
-
int pos=bs.searchRecursive(sortedData, 0, length-1, findValue);
-
System.out.println("Recursice:"+findValue+" found in pos "+pos+";count:"+bs.getrCount());
-
int pos2=bs.searchLoop(sortedData, findValue);
-
-
System.out.println("Loop:"+findValue+" found in pos "+pos+";count:"+bs.getlCount());
-
}
-
}
5、总结:这种查找方式的使用场合为已排序的数组。可以发现递归和循环的次数是一样的