java - 排序数组中的线性搜索 - Java

标签 java arrays linear-search

我想制作一个程序,在排序数组中进行线性搜索,并可以输出找到搜索项的不同位置。目前,我的程序仅输出找到搜索项的第一个位置,因此这里是我的程序现在所做的示例:

Enter number of elements
5
Enter 5 integers
1
3
3
9
15
Enter value to find
3
3 is present at location 2.

现在的问题是 3 位于位置 2 和 3 上,这就是我想在程序中编辑的内容,但我不知道该怎么做。

这是我的程序的代码:

import java.util.Scanner;
 class LinearSearchArray1 {
    public static void main(String args[]){
        int c, n, search, array[];

        Scanner in = new Scanner(System.in);
        System.out.println("Enter number of elements");
        n = in.nextInt(); 
        array = new int[n];

        System.out.println("Enter " + n + " integers");

        for (c = 0; c < n; c++)
        array[c] = in.nextInt();

        System.out.println("Enter value to find");
        search = in.nextInt();

        for (c = 0; c < n; c++)
        {
            if (array[c] == search)     /* Searching element is present */
            {
             System.out.println(search + " is present at location " + (c + 1) + ".");
            break;
        }
    }
    if (c == n)  /* Searching element is absent */
        System.out.println(search + " is not present in array.");
    }
}

最佳答案

...
System.out.println("Enter value to find");
search = in.nextInt();

boolean exists = false;

for (c = 0; c < n; c++)
{
  if (array[c] == search)     /* Searching element is present */
  {
     System.out.println(search + " is present at location " + (c + 1) + ".");
     exists = true;
  }
}

if (!exists)  /* Searching element is absent */
  System.out.println(search + " is not present in array.");

您需要删除break;语句。否则,一旦找到第一个值,循环就会中断,并且永远不会到达下一个匹配项。

关于java - 排序数组中的线性搜索 - Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34452878/

相关文章:

java - JPA/Eclipse链接 : Joined WHERE query does not give expected result

php - 从排序数组 PHP 返回键的顺序

arrays - O(1) 和 O(n) 之间的线性搜索差异

java - 在 Android Studio 的 TextView 中设置文本时出现问题

java - 应用程序的 CPU 使用率比其他正常 Web View 高

java - 从 .csv 文件中删除一行?

python - python中减去两个数组,类似于matlab中的bsxfun

Python 在数组列表中搜索字符串

java - 查找数组中的字母

algorithm - 我们能否找到元素是否存在于数组 {1,2,...,n} 中,其中元素为 Θ(m) 中的 m 个不同元素?