Java Online Compiler
Example: Array Element Frequency using Arrays.sort() in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// Array Element Frequency using Arrays.sort() import java.util.Arrays; import java.util.Scanner; // Main class containing the entry point of the program public class Main { public static void main(String[] args) { // Step 1: Initialize the array int[] arr = {10, 20, 20, 10, 10, 30, 40, 50, 20, 40}; // Step 2: Sort the array Arrays.sort(arr); // After sorting, arr becomes: [10, 10, 10, 20, 20, 20, 30, 40, 40, 50] // Step 3: Iterate through the sorted array to count frequencies System.out.println("Element Frequencies:"); for (int i = 0; i < arr.length; i++) { // Step 3a: Initialize count for the current element int count = 1; // Step 3b: Count consecutive occurrences of the current element // while (i + 1 < arr.length) checks if there's a next element // arr[i] == arr[i + 1] checks if the next element is the same while (i + 1 < arr.length && arr[i] == arr[i + 1]) { count++; i++; // Move to the next identical element } // Step 3c: Print the frequency of the unique element (arr[i] after counting) System.out.println(arr[i] + ": " + count + " times"); } } }
Output
Clear
ADVERTISEMENTS