Sort Elements by Frequency in JavaAn array of integers is given. Some elements of the array are repeated. Our task is to return an array or list of the provided elements in the decreasing order of their frequency of occurrence. In other words, the element which has the highest frequency of occurrence should come first. If the frequency of occurrence of any two elements matches, then the element that comes first in the input array should come first in the output array. Example 1: Input: inputArr[] = {12, 16, 15, 12, 12, 18, 15, 18, 16, 18, 18} Output: resultArr[] = {18, 18, 18, 18, 12, 12, 12, 16, 16, 15, 15} Explanation: Element 18 has the heighest frequency of occurrence, as its frequency count is 4. Then, element 12 has the heighest frequency of occurrence, as its frequency count is 3. Then, there is a tie between the frequency of occurrence of elements 16 and 15. Since, the element 16 occurs first therefore the element 16 has been put before the element 15. Example 2: Input: inputArr[] = {19, 20, 17, 45, 34, 3, 2, 1, 89, 56, 80, 85, 90} Output: resultArr[] = {19, 20, 17, 45, 34, 3, 2, 1, 89, 56, 80, 85, 90} Explanation: Each element has the same frequency of occurrence, which is 1. Therefore, the order in which the elements are there in the input array is the same as the order in which the elements are occurring in the output array. ApproachThe concept is to sort the element on the basis of the highest to the lowest occurrence of frequency of elements. In order to avoid conflict, maintain the occurrence index of the elements on the basis of their occurrence in the input array. AlgorithmStep 1: The concept is to implement the customized comparison method in order to solve the problem. Let the two elements that have to be compared be 'n1' and 'n2'. Then.
Step 2: For each element, put it into the dictionary along with its frequency and the index of its first occurrence in the input array. Step 3: Sort the values of elements on the basis of a custom comparator and eventually return the sorted list having the arranged elements. ImplementationObserve the implementation of the above algorithm. FileName: SortEleByFreq.java Output: The input array is: 12 16 15 12 12 18 15 18 16 18 18 After sorting by frequency of occurrences, the array becomes: 18 18 18 18 12 12 12 16 16 15 15 The input array is: 19 20 17 45 34 3 2 1 89 56 80 85 90 After sorting by frequency of occurrences, the array becomes: 19 20 17 45 34 3 2 1 89 56 80 85 90 Complexity Analysis: Since we are applying sorting, therefore the time complexity of the program is O(n * log(n)). We have also created an array list for storing the results. Thus making the space complexity O(n), where n denotes the total number of elements present in the input array.
Next TopicBeautiful Array in Java
|