在一维数组中搜索

时间:2021-06-22 12:33:04

I've managed to search in the array, but how do i display the location of the value searched in the array for the code below?

我已经设法在数组中搜索,但是如何显示数组中搜索的值的位置以获取下面的代码?

import javax.swing.*;
import java.util.Arrays;

public class Listahan {

    public static void main(String[] args){
        int list1[] = {1,3,2,5,7,8,5,6,9,4};
        int list2[] = {2,1,4,3,2,1,4,2,0,2};
        int list3[] = new int[10];
        int a;

        System.out.print("List1: ");
        for(a=0; a<10; a++){
            System.out.print(list1[a]+" ");
        }
        System.out.print("\nList2: ");
        for(a=0; a<10; a++){
            System.out.print(list2[a]+" ");
        }
        System.out.print("\nList3: ");
        for(a=0; a<10; a++){
            list3[a]=list1[a]+list2[a];
            System.out.print(list3[a]+" ");
        }

        int searchValue = Integer.parseInt(JOptionPane.showInputDialog("Input a value to search in List3: "));
        int Result = Arrays.binarySearch(list3,searchValue);

        if(Result!=-3){
            System.out.println("\n\nThe value "+searchValue+" is in List3!");
            System.out.println("There are "+Result+" of it in List3.");

        }else{
            System.out.println("\n"+searchValue+" cannot be found in List3.");
        }
    }


}

for example if i searched for 9, the output would be:

例如,如果我搜索9,输出将是:

The value 9 is in List3!
The are 4 of it in List3.
Located at: list3[4], list3[5], list3[6], list3[8]

值9在List3中! List3中有4个。位于:list3 [4],list3 [5],list3 [6],list3 [8]

4 个解决方案

#1


6  

There are a few things going on in the code that needs to be pointed out.

代码中有一些事情需要指出。

  1. A binary search works only on sorted lists.
  2. 二进制搜索仅适用于已排序的列表。
  3. The return value of the Arrays.binarySearch method is a position, rather than occurrences.
  4. Arrays.binarySearch方法的返回值是一个位置,而不是出现位置。

A binary search works only on sorted lists.

二进制搜索仅适用于已排序的列表。

In the code above, the lists list1, list2, and list3 are all unsorted lists. The binary search algorithm has a requirement that the list that it performs the search on must be sorted prior to applying the search algorithm.

在上面的代码中,列表list1,list2和list3都是未排序的列表。二进制搜索算法要求必须在应用搜索算法之前对其执行搜索的列表进行排序。

This requirement is noted in the Javadoc for the Arrays.binarySearch method:

在Arvas.binarySearch方法的Javadoc中注明了此要求:

Searches the specified array of bytes for the specified value using the binary search algorithm. The array must be sorted (as by the sort(int[]) method) prior to making this call. If it is not sorted, the results are undefined. If the array contains multiple elements with the specified value, there is no guarantee which one will be found.

使用二进制搜索算法在指定的字节数组中搜索指定的值。在进行此调用之前,必须对数组进行排序(如sort(int [])方法)。如果未排序,则结果未定义。如果数组包含具有指定值的多个元素,则无法保证将找到哪个元素。

[Emphasis added]

[强调补充]

The return value of a the Arrays.binarySearch method is a position, rather than occurrences

Arrays.binarySearch方法的返回值是一个位置,而不是出现位置

Once again, there is a problem with your expectations for how the binarySearch method works.

再一次,您对binarySearch方法的工作方式存在问题。

int Result = Arrays.binarySearch(list3,searchValue);

// .. other code ..

System.out.println("There are "+Result+" of it in List3.");

The above line of code, the return value from the binarySearch method, which is a position at which the specified element was found, is being used as if it is the number of occurrences of that element in the list.

上面的代码行,即binarySearch方法的返回值,它是找到指定元素的位置,正在使用它,就像它是列表中该元素的出现次数一样。

Furthermore, the if statement that is using the Return variable is probably working due to programming by coincidence:

此外,使用Return变量的if语句可能由于巧合编程而起作用:

    int Result = Arrays.binarySearch(list3,searchValue);

    if(Result!=-3){  // What does the -3 signify??
       // do something
    }else{
       // do something
    }

According to the Arrays.binarySearch javadoc, that method will return a non-zero value if the specified element is found in the list. It returning a value that is not -3 does not signify any specific return state -- therefore, this code is probably just running as a consequence of the list containing values in a certain way, so the code will break as soon as either list1 or list2 is changed at all.

根据Arrays.binarySearch javadoc,如果在列表中找到指定的元素,该方法将返回非零值。它返回一个不是-3的值并不表示任何特定的返回状态 - 因此,这个代码可能只是由于列表以某种方式包含值而运行,因此代码将在list1或list2完全改变了。

You'll want to take a look at the Javadocs of the Arrays.binarySearch method to see what exactly that method will return for you.

您将需要查看Arrays.binarySearch方法的Javadoc,以了解该方法将为您返回的确切内容。

Additional note

附加说明

As an additional note, if you wish to show the number of occurrences and positions at which the specified elements occurs, you might be better off just performing a for loop on the list, and checking each element if they are equals to each other.

另外需要注意的是,如果要显示指定元素出现的次数和位置,最好只在列表上执行for循环,并检查每个元素是否相等。

Here's a bit of pseudocode:

这里有一些伪代码:

for each element in list:
  is the element the element we're looking for?
    if yes, then increment the occurrences counter
    if yes, then print out the current position

Final note about the coding style

关于编码风格的最后说明

And, as a final note, the coding style could be improved a bit to make things easier to read and to conform to the Java coding standards.

并且,作为最后一点,编码风格可以稍微改进,以使事物更容易阅读并符合Java编码标准。

Add some spaces around punctuations

在标点符号周围添加一些空格

    int list1[] = {1,3,2,5,7,8,5,6,9,4};

    for(a=0; a<10; a++){
        System.out.print(list1[a]+" ");
    }

If we were writing in English, we add spaces after the punctuation to make it easier to read. We should do the same when coding to make the code easier to read. Adding spaces after commas and operators should make things a bit easier on the eyes:

如果我们用英文写作,我们在标点符号后添加空格以便于阅读。编码时我们应该这样做,以使代码更容易阅读。在逗号和运算符之后添加空格应该使眼睛更容易:

    int list1[] = {1, 3, 2, 5, 7, 8, 5, 6, 9, 4};

    for(a = 0; a < 10; a++) {
        System.out.print(list1[a] + " ");
    }

Secondly, the variable names should start with lower-case, so the Return variable should be something like returnValue or better yet position, as the Arrays.binarySearch method returns a position at which the element was found.

其次,变量名应该以小写字母开头,因此返回变量应该类似于returnValue或更好的位置,因为Arrays.binarySearch方法返回找到元素的位置。

For more information, please take a look at the Code Conventions for the Java Programming Language.

有关更多信息,请查看Java编程语言的代码约定。

#2


2  

Attention: the Arrays.binarySearch method assumes that your array is sorted ... which it is not.

注意:Arrays.binarySearch方法假定您的数组已排序......它不是。

#3


0  

System.out.println("There are "+**Result**+" of it in List3.");

Your result variable isn't the number 9's in the array it's the insertion point.

结果变量不是数组中的数字9,而是插入点。

Arrays.binraySearch() returns the insertion point -- coincidentally what you're looking for

Arrays.binraySearch()返回插入点 - 巧合的是你正在寻找的东西

http://download.oracle.com/javase/6/docs/api/java/util/Arrays.html#binarySearch(int[], int)

http://download.oracle.com/javase/6/docs/api/java/util/Arrays.html#binarySearch(int [],int)

The insertion point is defined as the point at which the key would be inserted into the array

插入点定义为将密钥插入阵列的点

Also your array must be sorted before using a binary search

在使用二进制搜索之前,还必须对数组进行排序

#4


0  

Since this is homework, you'll need to do some research to find the full solution. Read up on the return value of the Arrays.binarySearch() method. Also be sure to pay attention to the input parameters as described in the docs:

由于这是家庭作业,您需要做一些研究才能找到完整的解决方案。阅读Arrays.binarySearch()方法的返回值。另外一定要注意文档中描述的输入参数:

Java Arrays reference

Java Arrays参考

#1


6  

There are a few things going on in the code that needs to be pointed out.

代码中有一些事情需要指出。

  1. A binary search works only on sorted lists.
  2. 二进制搜索仅适用于已排序的列表。
  3. The return value of the Arrays.binarySearch method is a position, rather than occurrences.
  4. Arrays.binarySearch方法的返回值是一个位置,而不是出现位置。

A binary search works only on sorted lists.

二进制搜索仅适用于已排序的列表。

In the code above, the lists list1, list2, and list3 are all unsorted lists. The binary search algorithm has a requirement that the list that it performs the search on must be sorted prior to applying the search algorithm.

在上面的代码中,列表list1,list2和list3都是未排序的列表。二进制搜索算法要求必须在应用搜索算法之前对其执行搜索的列表进行排序。

This requirement is noted in the Javadoc for the Arrays.binarySearch method:

在Arvas.binarySearch方法的Javadoc中注明了此要求:

Searches the specified array of bytes for the specified value using the binary search algorithm. The array must be sorted (as by the sort(int[]) method) prior to making this call. If it is not sorted, the results are undefined. If the array contains multiple elements with the specified value, there is no guarantee which one will be found.

使用二进制搜索算法在指定的字节数组中搜索指定的值。在进行此调用之前,必须对数组进行排序(如sort(int [])方法)。如果未排序,则结果未定义。如果数组包含具有指定值的多个元素,则无法保证将找到哪个元素。

[Emphasis added]

[强调补充]

The return value of a the Arrays.binarySearch method is a position, rather than occurrences

Arrays.binarySearch方法的返回值是一个位置,而不是出现位置

Once again, there is a problem with your expectations for how the binarySearch method works.

再一次,您对binarySearch方法的工作方式存在问题。

int Result = Arrays.binarySearch(list3,searchValue);

// .. other code ..

System.out.println("There are "+Result+" of it in List3.");

The above line of code, the return value from the binarySearch method, which is a position at which the specified element was found, is being used as if it is the number of occurrences of that element in the list.

上面的代码行,即binarySearch方法的返回值,它是找到指定元素的位置,正在使用它,就像它是列表中该元素的出现次数一样。

Furthermore, the if statement that is using the Return variable is probably working due to programming by coincidence:

此外,使用Return变量的if语句可能由于巧合编程而起作用:

    int Result = Arrays.binarySearch(list3,searchValue);

    if(Result!=-3){  // What does the -3 signify??
       // do something
    }else{
       // do something
    }

According to the Arrays.binarySearch javadoc, that method will return a non-zero value if the specified element is found in the list. It returning a value that is not -3 does not signify any specific return state -- therefore, this code is probably just running as a consequence of the list containing values in a certain way, so the code will break as soon as either list1 or list2 is changed at all.

根据Arrays.binarySearch javadoc,如果在列表中找到指定的元素,该方法将返回非零值。它返回一个不是-3的值并不表示任何特定的返回状态 - 因此,这个代码可能只是由于列表以某种方式包含值而运行,因此代码将在list1或list2完全改变了。

You'll want to take a look at the Javadocs of the Arrays.binarySearch method to see what exactly that method will return for you.

您将需要查看Arrays.binarySearch方法的Javadoc,以了解该方法将为您返回的确切内容。

Additional note

附加说明

As an additional note, if you wish to show the number of occurrences and positions at which the specified elements occurs, you might be better off just performing a for loop on the list, and checking each element if they are equals to each other.

另外需要注意的是,如果要显示指定元素出现的次数和位置,最好只在列表上执行for循环,并检查每个元素是否相等。

Here's a bit of pseudocode:

这里有一些伪代码:

for each element in list:
  is the element the element we're looking for?
    if yes, then increment the occurrences counter
    if yes, then print out the current position

Final note about the coding style

关于编码风格的最后说明

And, as a final note, the coding style could be improved a bit to make things easier to read and to conform to the Java coding standards.

并且,作为最后一点,编码风格可以稍微改进,以使事物更容易阅读并符合Java编码标准。

Add some spaces around punctuations

在标点符号周围添加一些空格

    int list1[] = {1,3,2,5,7,8,5,6,9,4};

    for(a=0; a<10; a++){
        System.out.print(list1[a]+" ");
    }

If we were writing in English, we add spaces after the punctuation to make it easier to read. We should do the same when coding to make the code easier to read. Adding spaces after commas and operators should make things a bit easier on the eyes:

如果我们用英文写作,我们在标点符号后添加空格以便于阅读。编码时我们应该这样做,以使代码更容易阅读。在逗号和运算符之后添加空格应该使眼睛更容易:

    int list1[] = {1, 3, 2, 5, 7, 8, 5, 6, 9, 4};

    for(a = 0; a < 10; a++) {
        System.out.print(list1[a] + " ");
    }

Secondly, the variable names should start with lower-case, so the Return variable should be something like returnValue or better yet position, as the Arrays.binarySearch method returns a position at which the element was found.

其次,变量名应该以小写字母开头,因此返回变量应该类似于returnValue或更好的位置,因为Arrays.binarySearch方法返回找到元素的位置。

For more information, please take a look at the Code Conventions for the Java Programming Language.

有关更多信息,请查看Java编程语言的代码约定。

#2


2  

Attention: the Arrays.binarySearch method assumes that your array is sorted ... which it is not.

注意:Arrays.binarySearch方法假定您的数组已排序......它不是。

#3


0  

System.out.println("There are "+**Result**+" of it in List3.");

Your result variable isn't the number 9's in the array it's the insertion point.

结果变量不是数组中的数字9,而是插入点。

Arrays.binraySearch() returns the insertion point -- coincidentally what you're looking for

Arrays.binraySearch()返回插入点 - 巧合的是你正在寻找的东西

http://download.oracle.com/javase/6/docs/api/java/util/Arrays.html#binarySearch(int[], int)

http://download.oracle.com/javase/6/docs/api/java/util/Arrays.html#binarySearch(int [],int)

The insertion point is defined as the point at which the key would be inserted into the array

插入点定义为将密钥插入阵列的点

Also your array must be sorted before using a binary search

在使用二进制搜索之前,还必须对数组进行排序

#4


0  

Since this is homework, you'll need to do some research to find the full solution. Read up on the return value of the Arrays.binarySearch() method. Also be sure to pay attention to the input parameters as described in the docs:

由于这是家庭作业,您需要做一些研究才能找到完整的解决方案。阅读Arrays.binarySearch()方法的返回值。另外一定要注意文档中描述的输入参数:

Java Arrays reference

Java Arrays参考