Java Online Compiler
Example: CountDistinctElementsUsingSorting in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// CountDistinctElementsUsingSorting import java.util.Arrays; public class Main { public static void main(String[] args) { // Step 1: Define the input array int[] arr = {10, 20, 10, 30, 40, 20, 50}; // Step 2: Handle edge cases for empty or single-element arrays if (arr.length == 0) { System.out.println("Original Array: " + Arrays.toString(arr)); System.out.println("Number of distinct elements (Sorting): 0"); return; } // Step 3: Sort the array Arrays.sort(arr); // Step 4: Initialize distinct count and iterate through the sorted array int distinctCount = 1; // At least one element is distinct if array is not empty for (int i = 1; i < arr.length; i++) { // If the current element is different from the previous one, it's a new distinct element if (arr[i] != arr[i-1]) { distinctCount++; } } // Step 5: Print the result System.out.println("Original Array: " + Arrays.toString(arr)); System.out.println("Sorted Array: " + Arrays.toString(arr)); System.out.println("Number of distinct elements (Sorting): " + distinctCount); } }
Output
Clear
ADVERTISEMENTS