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

Join the discussion
Registration is free. Ask a follow-up in this thread, or start your own.
3 replies · 4K views
pumas
Messages
15
Reaction score
0
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:
 
Physics news on Phys.org
If its sorted then it's pretty easy, just walk through the array checking if each value is the same as the previous one.
 
Something like this:
Code:
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;
}
 
Thank you for your help :smile: