Java - 比较线性搜索和二分搜索的性能

标签 java arrays binary-search

<分区>

Possible Duplicate:
What is the difference between Linear search and Binary search?

Write a program that generates 20 random integers within the range from 0 to 100. Sort the array in descending order. Then, accepts an integer input from the user. Then, search the array using this number. Compare the performance of linear search and binary search.

这是我的代码

import java.util.Arrays;    
import java.util.Scanner;

public class search {

    public static void main(String args[]) {
        int[] num = new int[20];
        for (int i = 0; i < num.length; i++) {

            num[i] = (int) (Math.random() * 101);
        }
        System.out.println("A list of 20 random intergers with 0 - 100");
        System.out.println(Arrays.toString(num));
        for (int j = 1; j < num.length; j++) {
            for (int k = 0; k < num.length - 1; k++) {
                if (num[k] < num[k + 1]) {
                    int hold = num[k + 1];
                    num[k + 1] = num[k];
                    num[k] = hold;
                }
            }

        }
        System.out.println("Array in descending order");
        System.out.println(Arrays.toString(num));
        Scanner input = new Scanner(System.in);
        System.out.print("Enter a number to search: ");
        int num2 = input.nextInt();
        int loop = 0;
        for ( int cnt = 0; cnt < num.length; cnt++ )
        {
            if ( num[cnt] == num2 )
            {
                loop = cnt;
                System.out.println(num2+ " found"); 
          }

        }
        System.out.println("Linear search - "+loop+ " loop(s)");
        int loop2 = 0;
        int low = 0;   // low element subscript
        int high = num.length - 1;  // high element subscript
        int middle;    // middle element subscript
        while ( low <= high ) {
            middle = ( low + high ) / 2;
            if ( num2 == num[ middle ] ) { 

            }
            else if ( num2 > num[ middle ] )
            {
              low = middle +1;
               loop2++;
            }
            else{
              high = middle - 1;   
               loop2++;
            }                      
      }
        System.out.println("Binary search - "+loop2+ " loop(s)");
    }
}

我可以获得线性搜索的循环次数。但是,我无法获得二进制搜索循环数。

最佳答案

您的二分查找缺少中断:

        if ( num2 == num[ middle ] ) { 

        }

您的二进制搜索也是按升序排列的,但实际上是按降序排列的!要么反转排序,要么调整搜索算法。

关于Java - 比较线性搜索和二分搜索的性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12996928/

相关文章:

PostgreSQL 中自定义类型的数组

algorithm - 我如何使用霍尔逻辑证明这种二进制搜索算法是正确的?

java - 我如何将此代码转换为 java 8 流?

java - 如何更改谷歌 token 过期时间?

arrays - Google 应用程序脚本 - 获取数组中每个元素的 A1 单元格符号

c++ - 前或后测试循环?

arrays - 在具有重复项的排序数组中查找 A[i]=i

c# - 最接近值的元组的二进制搜索列表 >=

java - 延迟关闭的 DB2 JDBC native 驱动程序问题

java - Sonar 违规 : "Method may fail to close stream on exception"