Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.LinkedHashMap;
- /*
- * Given an array of integers, sort the array according to frequency of elements.
- * For example, if the input array is {2, 3, 2, 4, 5, 12, 2, 3, 3, 3, 12}, then
- * modify the array to {3, 3, 3, 3, 2, 2, 2, 12, 12, 4, 5}.
- */
- public class frequencySort1 {
- public static void main(String[] args) {
- int[] unsortedArray = { 2,12,3,2,4,2,3,3,3,12,5 };
- LinkedHashMap<Integer, Integer> valueAndItsCount = new LinkedHashMap<Integer, Integer>();
- for(int x : unsortedArray) {
- if(valueAndItsCount.containsKey(x)) {
- int xCount = valueAndItsCount.get(x);
- xCount++;
- valueAndItsCount.put(x, xCount);
- }
- else {
- valueAndItsCount.put(x, 1);
- }
- }
- int maxCount = 0;
- int theKey = 0;
- while(!valueAndItsCount.isEmpty()) {
- for(int x : valueAndItsCount.keySet()) {
- if(valueAndItsCount.get(x) > maxCount) {
- maxCount = valueAndItsCount.get(x);
- theKey = x;
- }
- }
- for(int i=0; i < maxCount; i++) {
- System.out.print(theKey + " ");
- }
- valueAndItsCount.remove(theKey);
- maxCount = 0;
- }
- } //end main
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement