Deep
Deep

Reputation: 98

Binary Search in Array not working

I am working on a program that will get user input and then store it in an array. Then, it will search the array to see if the number entered by the user is a duplicate or not. For some reason binarySearch is not detecting duplication.

My code is:

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

public class Duplicate_Elimination 
{
   public static void main(String[] args) 
   {

   int [] numbers = new int[5]; // create an array
   Scanner input = new Scanner(System.in); // create a Scanner

       // Ask user for 5 numbers
       for (int i = 0; i < 5; i++)
       {
           // ask user to type the number
           System.out.printf("Please type number %d:",i+1);
           int number = input.nextInt(); // get user input and store it in number variable

           // check if the number entered is already stored
           int location = Arrays.binarySearch(numbers,number);

           // store the value inside number variable in numbers array 
           numbers[i] = number;

           showArray(numbers);

           // if there is any similarity between numbers, print error message
           if (location >= 0)
               System.out.printf("%s%n","error");
       } // end for
   }

   // this method will show what's in the array
   public static void showArray(int[] numbers)
   {
       System.out.printf("%n%n"); // print black spaces

       // print all the numbers stored in the array
       for(int digit: numbers)
       {
           System.out.printf("%d",digit);
       }

       System.out.printf("%n"); // print black space
   }
}

I tried my very best to solve but when ever I type 1 as all my numbers, it only show duplication after typing like 3 numbers. It should detect duplication after each entry. Can you please help me figure out what's wrong with my code. I will really appreciate that.

Thanks!!

Upvotes: 1

Views: 246

Answers (2)

Aaron Ferguson
Aaron Ferguson

Reputation: 1

From what I can see I think taking out the similarity by commenting it out should work.

showArray(numbers);

       // if there is any similarity between numbers, print error message
       //if (location >= 0)
           //System.out.printf("%s%n","error");
   } // end for
 }

Upvotes: 0

M. Shaw
M. Shaw

Reputation: 1742

From the java.util.Arrays documentation:

public static int binarySearch(int[] a, int key)

Searches the specified array of ints 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.

So you need to sort the array after every insertion.

Upvotes: 3

Related Questions