CompSci.rocks
LearnJava

Unique Algorithm in Java

Learn how to find whether an array contains unique values in Java using the unique algorithm.

Need to check whether all values in a Java array are unique? Here you go.

public boolean unique(int[] ray) {
    for (int i = 0; i < ray.length; i++) {
        for (int j = i + 1; j < ray.length; j++) {
            if (ray[i] == ray[j]) {
                return false;
            }
        }
    }
    return true;
}

This isn't a super efficient solution, but it does work.

What we're doing is starting at the first element in the array. From there we start a nested loop starting at the next element and look at every element from that point. If there's a match, then the method returns false because a match means that all elements aren't unique. If we get to the end of the loop and there's no match, then we return true.

Array Algorithms

A series of algorithms used in array manipulation.

  1. Introduction
  2. Minimum / Maximum algorithm in Java
  3. Java sum algorithm for arrays
  4. Java Array Average Algorithm
  5. Are values in Java array unique?
  6. Swap array values
  7. Java Array Linear Search Algorithm