Test with Sorted Array
In this final step, we will explore another approach to finding duplicates, specifically when the array is sorted. If an array is sorted, duplicate elements will always be adjacent to each other. This allows for a very simple and efficient way to find duplicates by just comparing adjacent elements.
First, let's create a new Java file named FindDuplicatesSorted.java
in your ~/project
directory.
Open the FindDuplicatesSorted.java
file in the Code Editor and add the following Java code:
import java.util.Arrays;
public class FindDuplicatesSorted {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 2, 7, 8, 8, 3};
// First, sort the array
Arrays.sort(numbers);
System.out.println("Finding duplicate elements in a sorted array:");
// Iterate through the sorted array and compare adjacent elements
for (int i = 0; i < numbers.length - 1; i++) {
// If the current element is equal to the next element, it's a duplicate
if (numbers[i] == numbers[i + 1]) {
System.out.println("Duplicate found: " + numbers[i]);
}
}
}
}
Let's examine the key parts of this code:
import java.util.Arrays;
: This line imports the Arrays
class, which provides utility methods for arrays, including sorting.
Arrays.sort(numbers);
: This line sorts the numbers
array in ascending order.
for (int i = 0; i < numbers.length - 1; i++)
: This loop iterates through the sorted array. We loop up to numbers.length - 1
because we are comparing the current element (numbers[i]
) with the next element (numbers[i + 1]
).
if (numbers[i] == numbers[i + 1])
: This condition checks if the current element is equal to the next element. If they are the same, it means we have found a duplicate.
Save the file (Ctrl + S
or Cmd + S
).
Now, compile the Java code in the Terminal:
javac FindDuplicatesSorted.java
If the compilation is successful, run the program:
java FindDuplicatesSorted
You should see the output listing the duplicate elements found. Notice that because the array is sorted, the duplicates will appear consecutively in the output.
This method is very efficient for sorted arrays as it only requires a single pass through the array after sorting. However, the initial sorting step itself has a time cost, which depends on the sorting algorithm used by Arrays.sort()
. For primitive types like int
, Java's Arrays.sort()
uses a dual-pivot quicksort, which has an average time complexity of O(n log n).
You have now explored three different ways to find duplicates in an array in Java: using nested loops, using a HashSet
, and using a sorted array. Each method has its own trade-offs in terms of simplicity, efficiency, and requirements (like the array being sorted). Understanding these different approaches is valuable for choosing the most suitable method for a given problem.