Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

How to search for duplicate values in an array of integers?

  1. Jun 30, 2008 #1
    I'm trying to search for duplicate values in a array of integers in Java. The array of intergers is sorted. Could anyone give me an idea on how to get started. :confused:
     
  2. jcsd
  3. Jun 30, 2008 #2

    mgb_phys

    User Avatar
    Science Advisor
    Homework Helper

    If its sorted then it's pretty easy, just walk through the array checking if each value is the same as the previous one.
     
  4. Jun 30, 2008 #3

    CRGreathouse

    User Avatar
    Science Advisor
    Homework Helper

    Something like this:
    Code (Text):
    boolean has_duplicate (int[] arr) {
      int lim = arr.length - 1;
      for (int i = 0; i < lim;)
        if (arr[i] == arr[++i])
          return true;
      return false;
    }
     
  5. Jun 30, 2008 #4
    Thank you for your help :smile:
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook

Have something to add?



Similar Discussions: How to search for duplicate values in an array of integers?
Loading...