Advertisement
scottashipp

Frequency Sort Example

May 7th, 2013
594
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.13 KB | None | 0 0
  1. import java.util.LinkedHashMap;
  2.  
  3. /*
  4.  * Given an array of integers, sort the array according to frequency of elements.
  5.  * For example, if the input array is {2, 3, 2, 4, 5, 12, 2, 3, 3, 3, 12}, then
  6.  * modify the array to {3, 3, 3, 3, 2, 2, 2, 12, 12, 4, 5}.
  7.  */
  8. public class frequencySort1 {
  9.    
  10.     public static void main(String[] args) {
  11.         int[] unsortedArray = { 2,12,3,2,4,2,3,3,3,12,5 };
  12.        
  13.         LinkedHashMap<Integer, Integer> valueAndItsCount = new LinkedHashMap<Integer, Integer>();
  14.        
  15.         for(int x : unsortedArray) {
  16.             if(valueAndItsCount.containsKey(x)) {
  17.                 int xCount = valueAndItsCount.get(x);
  18.                 xCount++;
  19.                 valueAndItsCount.put(x, xCount);
  20.             }
  21.             else {
  22.                 valueAndItsCount.put(x, 1);
  23.             }
  24.         }
  25.        
  26.         int maxCount = 0;
  27.         int theKey = 0;
  28.         while(!valueAndItsCount.isEmpty()) {
  29.            
  30.        
  31.             for(int x : valueAndItsCount.keySet()) {
  32.                 if(valueAndItsCount.get(x) > maxCount) {
  33.                     maxCount = valueAndItsCount.get(x);
  34.                     theKey = x;
  35.                 }
  36.             }
  37.            
  38.             for(int i=0; i < maxCount; i++) {
  39.                 System.out.print(theKey + " ");
  40.             }
  41.             valueAndItsCount.remove(theKey);
  42.             maxCount = 0;
  43.         }
  44.        
  45.     } //end main
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement