Java Online Compiler
Example: Remove Duplicates by Sorting in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// Remove Duplicates by Sorting import java.util.Arrays; public class Main { public static void main(String[] args) { int[] originalArray = {5, 2, 8, 2, 5, 1, 9, 8}; System.out.println("Original Array: " + Arrays.toString(originalArray)); // Step 1: Sort the original array // This brings duplicate elements together Arrays.sort(originalArray); System.out.println("Sorted Array: " + Arrays.toString(originalArray)); // Step 2: Create a temporary array to store unique elements // The maximum size for this temporary array is the original array's length int[] tempArray = new int[originalArray.length]; int uniqueCount = 0; // Tracks the number of unique elements // Step 3: Iterate through the sorted array if (originalArray.length > 0) { tempArray[uniqueCount++] = originalArray[0]; // Add the first element, which is always unique in its context for (int i = 1; i < originalArray.length; i++) { // If the current element is different from the last unique element added, it's a new unique element if (originalArray[i] != tempArray[uniqueCount - 1]) { tempArray[uniqueCount++] = originalArray[i]; } } } // Step 4: Create the final array with the correct size int[] arrayWithoutDuplicatesSorted = Arrays.copyOf(tempArray, uniqueCount); System.out.println("Array after removing duplicates (Sorted): " + Arrays.toString(arrayWithoutDuplicatesSorted)); } }
Output
Clear
ADVERTISEMENTS