bharathi - 2 years ago 173
Java Question

# Sort array based on count of occurrences in ascending order

How can I arrange the elements in an array based on the number of occurrences of that value in ascending order in java.

This is what I've tried:

``````int a[]={0,0,0,1,3,3,2,1,3,5,6,0};
int b=a.length;
for(int i=0;i<b;i++) {
for(int j=0;j<i;j++) {
int temp;
if( a[j]>a[i]) {
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}

for(int r=0;r<a.length;r++) {
System.out.println(a[r]);
}
``````

Here's one approach to start you off could be based on the idea of keeping a count of how many times each integer in the initial array has occurred in a map. Once all the numbers have been counted, sort the map by order of ascending value, and then print the output of the map:

``````import java.util.ArrayList;
import java.util.HashMap;
import java.util.TreeMap;

public class SortCount {
public static void main(String[] args) {
int nums[] = {0,0,0,1,3,3,2,1,3,5,6,0};
HashMap<Integer,Integer> counts = new HashMap<Integer,Integer>();

for(int i = 0; i < nums.length; i++) {
if(counts.containsKey(nums[
Integer c = counts.get(nums[i]) + 1;
counts.put(nums[i], c);
}
else {
counts.put(nums[i],1);
}
}

ValueComparator<Integer,Integer> bvc = new ValueComparator<Integer,Integer>(counts);
TreeMap<Integer,Integer> sortedMap = new TreeMap<Integer,Integer>(bvc);
sortedMap.putAll(counts);

ArrayList<Integer> output = new ArrayList<Integer>();
for(Integer i : sortedMap.keySet()) {
for(int c = 0; c < sortedMap.get(i); c++) {
}
}

System.out.println(output.toString());
}
}
``````

Which uses a `Comparator` class to compare the values in a `Map`:

``````import java.util.Comparator;
import java.util.Map;

public class ValueComparator<T1,T2 extends Comparable<T2>> implements Comparator<T1> {
Map<T1,T2> base;
public ValueComparator(Map<T1,T2> base) {
this.base = base;
}

@Override
public int compare(T1 k1, T1 k2) {
T2 val1 = base.get(k1);
T2 val2 = base.get(k2);

return val1.compareTo(val2);
}
}
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download