Java Online Compiler
Example: Remove Duplicates Manually (Sorted Array) in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// Remove Duplicates Manually (Sorted Array) import java.util.Arrays; public class Main { public static void main(String[] args) { // Step 1: Define the array with duplicate elements int[] originalArray = {1, 2, 3, 2, 1, 4, 5, 4, 6}; System.out.println("Original Array: " + Arrays.toString(originalArray)); // Handle empty or single-element array edge case if (originalArray.length <= 1) { System.out.println("Array without Duplicates (Manual Sorted): " + Arrays.toString(originalArray)); return; } // Step 2: Sort the array Arrays.sort(originalArray); // Output: [1, 1, 2, 2, 3, 4, 4, 5, 6] System.out.println("Sorted Array: " + Arrays.toString(originalArray)); // Step 3: Create a temporary array to store unique elements int[] temp = new int[originalArray.length]; int j = 0; // Index for the temp array // Step 4: Iterate through the sorted array and copy unique elements for (int i = 0; i < originalArray.length - 1; i++) { if (originalArray[i] != originalArray[i + 1]) { temp[j++] = originalArray[i]; } } // Add the last element (which is always unique in comparison to the element before it) temp[j++] = originalArray[originalArray.length - 1]; // Step 5: Create a new array of the correct size and copy elements from temp int[] arrayWithoutDuplicates = Arrays.copyOf(temp, j); // Step 6: Print the array after removing duplicates System.out.println("Array without Duplicates (Manual Sorted): " + Arrays.toString(arrayWithoutDuplicates)); } }
Output
Clear
ADVERTISEMENTS