二分查找最大比较次数
程序员文章站
2021-12-23 21:07:42
...
对有序数组进行查找,一般采用折半查找,也叫二分查找。它的最大比较次数,或者查找一个数组中不存在的数据的最大比较次数,如下:
public class BinarySearchNum
{
private static int Length = 9;
public static void main(String[] args)
{
int size = 10;
int low = 1;
int high = 1;
for(int i=0; i<Length; i++)
{
high = size;
Compute(low, high);
size = size * 10;
}
}
public static void Compute(int low, int high)
{
int count = 0;
int temp = high;
while(low != high)
{
high = (low + high)/2;
count++;
}
System.out.println(temp + " " + count);
}
}
输出结果为(前面数字为数组大小,后面数字为最大比较次数):
10 4
100 7
1000 10
10000 14
100000 17
1000000 20
10000000 24
100000000 27
1000000000 30
后来想到一个问题,对有序数组的查找,是不是二分查找算法就是最快的呢?于是试了下“三分查找”,如下代码,结果比较次数比二分查找的次数多。如下代码:
public class TripleSearchNum
{
public static int Size = 1000;
public static void main(String[] args)
{
int low = 1;
int high = Size;
int count = 0;
while(low != high)
{
high = (low + high)/3;
count = count + 2;
}
System.out.println(count);
}
}
上一篇: MD5、SHA加密实体类