Finding the Frequency of Elements in an Array
Understanding Frequency Calculation
Finding the frequency of elements in an array involves counting the number of times each element appears.
We will explore three different methods to determine the frequency using Java.
Method 1: Using a Loop
This method iterates through the array and counts occurrences of each element.
import java.util.Arrays; public class FrequencyFinder { public static void findFrequency(int[] arr) { boolean[] visited = new boolean[arr.length]; Arrays.fill(visited, false); for (int i = 0; i < arr.length; i++) { if (visited[i]) continue; int count = 1; for (int j = i + 1; j < arr.length; j++) { if (arr[i] == arr[j]) { count++; visited[j] = true; } } System.out.println(arr[i] + " appears " + count + " times."); } } public static void main(String[] args) { int[] arr = {1, 2, 3, 2, 1, 3, 3}; findFrequency(arr); } }
1 appears 2 times.
2 appears 2 times.
3 appears 3 times.
Method 2: Using a HashMap
This method utilizes a HashMap to store frequencies.
import java.util.HashMap; public class FrequencyFinder { public static void findFrequency(int[] arr) { HashMapfreqMap = new HashMap<>(); for (int num : arr) { freqMap.put(num, freqMap.getOrDefault(num, 0) + 1); } for (var entry : freqMap.entrySet()) { System.out.println(entry.getKey() + " appears " + entry.getValue() + " times."); } } public static void main(String[] args) { int[] arr = {1, 2, 3, 2, 1, 3, 3}; findFrequency(arr); } }
1 appears 2 times.
2 appears 2 times.
3 appears 3 times.
Method 3: Using Sorting
This method sorts the array first and then counts occurrences.
import java.util.Arrays; public class FrequencyFinder { public static void findFrequency(int[] arr) { Arrays.sort(arr); for (int i = 0; i < arr.length; i++) { int count = 1; while (i < arr.length - 1 && arr[i] == arr[i + 1]) { count++; i++; } System.out.println(arr[i] + " appears " + count + " times."); } } public static void main(String[] args) { int[] arr = {1, 2, 3, 2, 1, 3, 3}; findFrequency(arr); } }
1 appears 2 times.
2 appears 2 times.
3 appears 3 times.