我正在尝试确定对线性和二进制搜索技术进行了多少比较。有人可以告诉我如何打印每种情况下循环发生的次数吗?例如,要在第一个数组中找到 5,循环只发生一次。
public static void main(String[] args) {
// TODO code application logic here
int[] values = {5, 8, 6, 2, 1, 7, 9, 3, 0, 4, 20, 50, 11, 22, 32, 120};
int[] valuesSorted = {1, 2, 3, 4, 5, 8, 16, 32, 51, 57, 59, 83, 90, 104};
DisplayArray(values);
DisplayArray(valuesSorted);
int index;
index = IndexOf(1, values);
System.out.println("1 is at values location " + index);
index = IndexOf(120, values);
System.out.println("120 is at values location " + index);
index = BinaryIndexOf(104, valuesSorted);
System.out.println("104 is at values Sorted location " + index);
index = BinaryIndexOf(90, valuesSorted);
System.out.println("90 is at values Sorted location " + index);
}
public static int IndexOf(int value, int[] array)
{
for (int i=0; i < array.length; i++)
{
if(array[i] == value)
return i;
}
return -1;
}
public static int BinaryIndexOf(int value, int [] array)
{
int start = 0;
int end = array.length -1;
int middle;
while (end >= start)
{
middle = (start + end ) /2;
if (array[middle]== value)
return middle;
if (array[middle]< value)
start = middle + 1;
else
end = middle - 1;
}
return -1;
}
public static void DisplayArray(int[] array)
{
for (int a : array)
{
System.out.print(a + " ");
}
System.out.println();
}
}