Remove Duplicate Elements From Unsorted Array And Print Sorted

By Saruque Ahamed Mollick

Now we are going to learn a java program to deal with unsorted array (or maybe a sorted or any kind of array).
An unsorted array means it will not contain the elements in a particular order.

By this below java program we can omit/remove all the duplicates elements from an array integer and we will print all the distinct elements in a sorted manner.

A Java Program To Find Duplicate Values In an Array

Algorithm for removing duplicate elements from any array and print the distinct elements in a sorted manner

Step 1: Take array size from the user by Scanner Class.
Step 2: Take elements from the user by using for loop.
Step 3: Sort the array using Arrays.sort() method.
Step 4: Remove Duplicate elements by passing parameters in “DuplicateRemoval(int array[], int n)” method.
Step 5: Print the elements finally.

Java Program To Remove Duplicates From Any Array

import java.util.Arrays;
import java.util.Scanner;
public class CodeSpeedy {
   public static int DuplicateRemoval(int array[], int n){  
        if (n==0 || n==1){  
            return n;  
        }    
        int k = 0;
        for (int i=0; i < n-1; i++){  
            if (array[i] != array[i+1]){  
                array[k++] = array[i];  
            }  
        }  
        array[k++] = array[n-1];  
        return k;  
    }  
       
    public static void main (String[] args) {  
        Scanner input=new Scanner(System.in);
        System.out.println("Enter the size of array:");
        int n=input.nextInt();
        
        int array[]=new int[n]; 
        System.out.println("Enter the elements one by one:");
        for (int s=0;s<array.length;s++){
            array[s]=input.nextInt();
        }
        Arrays.sort(array);
        int return_value= DuplicateRemoval(array, array.length);  
        System.out.println("Sorted Array after removing the Duplicate Elements:");
        for (int i=0; i<return_value; i++)  
           System.out.print(array[i]+" ");  
    }  
}

 

Output:

 

 

run:
Enter the size of array:
8
Enter the elements one by one:
5
2
6
1
2
5
9
6
Sorted Array after removing the Duplicate Elements:
1 2 5 6 9 BUILD SUCCESSFUL (total time: 17 seconds)

Merge (Combine) Two or More Arrays Into A Single Array In Java

Leave a Reply

Your email address will not be published. Required fields are marked *