Home > Software engineering >  I need to sort Character array based on another integer array. Below is my code
I need to sort Character array based on another integer array. Below is my code

Time:12-25

How to sort the ele array according to the freq array?

public class Comparator1 {

    public static void main(String[] args) {
        char[] ele = { 'a', 'b', 'c', 'd', 'e' };
        int[] freq = { 5, 4, 3, 2, 1 };
        
        System.out.println(Arrays.toString(ele));
    }

}

CodePudding user response:

In case you do not have duplications in freq array, you can use TreeMap:

public static char[] sort(char[] ele, int[] freq) {
    Map<Integer, Character> map = new TreeMap<>();

    for (int i = 0; i < ele.length; i  )
        map.put(freq[i], ele[i]);

    int i = 0;

    for (Character ch : map.values())
        ele[i  ] = ch;

    return ele;
}

Otherwise, you can use PriorityQueue:

public static char[] sort(char[] ele, int[] freq) {
    class Pair {

        final char ele;
        final int freq;

        public Pair(char ele, int freq) {
            this.ele = ele;
            this.freq = freq;
        }

    }

    Queue<Pair> queue = new PriorityQueue<>(Comparator.comparingInt(pair -> pair.freq));

    for (int i = 0; i < ele.length; i  )
        queue.add(new Pair(ele[i], freq[i]));

    int i = 0;

    for (Pair pair : queue)
        ele[i  ] = pair.ele;

    return ele;
}

CodePudding user response:

Converting it into map can help u in better way as you can sort map easily. Try below code

    char ele[] = new char[] { 'a', 'b', 'c', 'd', 'e' };
    int freq[] = new int[] { 5, 4, 7, 2, 1 };
    int n=ele.length;
    //this will check whether both have same element or not 
    if(n!=freq.length)
        return;

    Map<Character,Integer> unsorted=new HashMap<>();
    //this will merge your both array into single map with key as char and freq as value
    for(int i=0;i<n;i  )
    {

        unsorted.put(ele[i],freq[i]);
    }
    
    Map<Character, Integer> sorted = new LinkedHashMap<>();
    unsorted.entrySet().stream()
            .sorted(Map.Entry.<Character, Integer>comparingByValue().reversed())
            .forEachOrdered(x -> sorted.put(x.getKey(), x.getValue()));
    sorted.forEach((k,v)->
    {

        System.out.println(k " --> " v);
    });

CodePudding user response:

Good you are learning java, Hope this works for both way of sorting

public static void main(String[] args) {
    char ele[] = new char[]{'a', 'b', 'c', 'd', 'e'};
    int freq[] = new int[]{5, 4, 3, 2, 1};
    Map<Character, Integer> inputMap = new HashMap<>();
    for (int i = 0; i < ele.length; i  ) {
         inputMap.put(ele[i],freq[i]);
    }
    System.out.println(inputMap);

    // sort in desc
    Map<Character, Integer> sortedDesc = new LinkedHashMap<>();
    inputMap.entrySet().stream()
            .sorted(Map.Entry.<Character, Integer>comparingByValue().reversed())
            .forEachOrdered(x -> sortedDesc.put(x.getKey(), x.getValue()));

    System.out.println(sortedDesc);
    System.out.println(sortedDesc.keySet());

    // sort in asc
    LinkedHashMap<Character, Integer> sortedAsc = new LinkedHashMap<>();
    inputMap.entrySet()
            .stream()
            .sorted(Map.Entry.comparingByValue())
            .forEachOrdered(x -> sortedAsc.put(x.getKey(), x.getValue()));
    System.out.println(sortedAsc);
    System.out.println(sortedAsc.keySet());

}

CodePudding user response:

I've made a simple and elegant solution to solve this. It is simple in the fact that it avoids any complex data structures like HashMaps or TreeMaps and just uses arrays. Enjoy :)

char ele[] = new char[] { 'a', 'd', 'c', 'e', 'b' };
Arrays.sort(ele);
int freq[] = new int[] { 2, 5, 3, 1, 4 };
char sortedEle[] = new char[ele.length];
int idxCounter = 0;
for (int i = 0; i < freq.length; i  ) {
   for (int j = 0; j < ele.length; j  ) {
       if (freq[i] == j   1) {
           sortedEle[idxCounter] = ele[j];
           idxCounter  ;
       }
    }
}
System.out.println(Arrays.toString(sortedEle));

Output

[b, e, c, a, d]
  • Related