开发者

Search in an One-dimensional Array

开发者 https://www.devze.com 2023-03-29 18:56 出处:网络
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?

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]+" ");
        }
        Sys开发者_StackOverflow中文版tem.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:

The value 9 is in List3!

The are 4 of it in List3.

Located at: list3[4], list3[5], list3[6], list3[8]


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. The return value of the Arrays.binarySearch method is a position, rather than occurrences.

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.

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

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.

[Emphasis added]

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

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

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.

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

    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.

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.

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.

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.

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.

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


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


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.

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

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


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:

Java Arrays reference

0

精彩评论

暂无评论...
验证码 换一张
取 消