java - 如何打印出循环发生的次数?

标签 java loops

我正在尝试确定线性搜索技术和二分搜索技术进行了多少次比较。有人可以告诉我如何打印出每种情况下循环发生的次数吗?例如,要在第一个数组中查找 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();
}

}

最佳答案

对于线性搜索,你可以这样做:

public static int IndexOf(int value, int[] array)
{
    for (int i=0; i < array.length; i++)
    {

        if(array[i] == value)
        {            
            System.out.println("Linear search: Number of comparisons = " + (i + 1));
            return i;
        }
    }

    return -1;
}

对于二分搜索,请执行以下操作:

public static int BinaryIndexOf(int value, int [] array)
{
    int start = 0;
    int end = array.length -1;
    int middle;
    int loopCount = 0;
    while (end >= start)
    {
        loopCount++;
        middle = (start + end ) /2;
        if (array[middle]== value)
        {
            System.out.println("Binary search: Number of times looped = " + loopCount); 
            return middle;
        }
        if (array[middle]< value)
            start = middle + 1;
        else 
            end = middle - 1;
    }
    System.out.println("Binary search: Number of times looped = " + loopCount);
    return -1;

}

关于java - 如何打印出循环发生的次数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13337446/

相关文章:

java - 如何为 Android 中所有单选按钮组中的所有单选按钮设置背景

python - 通过迭代更改列表的元素(python)

java - XMPP 服务器,smack API 连接

java - 如何从左到右计算表达式

java - FileInputStream.read(byte[]) 有什么问题?

PHP如何查找重复项

java - 将奇偶数与字符串分开

java - 数组列表对比较?

java - 沙盒静态字段

java - 在 Java 中重复提示直到字符串中的所有字符都可以接受