10
votes

Trier la matrice basée sur le nombre d'occurrences dans l'ordre croissant

Comment puis-je organiser les éléments dans un tableau en fonction du nombre d'occurrences de cette valeur en ordre croissant en Java.

C'est ce que j'ai essayé: p>

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]);
}


8 commentaires

Quel résultat voulez-vous? {0,0,0,0,1,1,2,3,3,3,5,6} ?


Pour construire sur le commentaire précédent: Voulez-vous trier le tableau?


Que signifie "basé sur le comte"? Ascendant si une longueur impaire, descendante si même la longueur ou quelque chose comme ça?


On dirait qu'il veut dire trier en fonction du nombre de fois que les clés sont présentes. Le tableau donné deviendrait alors {2,5,6,1,1,3,3,3,0,0,0,0}, car 2,5,6 sont présents une fois 1 deux fois ...


Je suis étonné de ce que la question de ce niveau soit posée par l'utilisateur avec plus de 130 questions à ce sujet, au sein d'il a demandé des choses assez avancées - par exemple - comment voir la vidéo de taille complète sur Android. La programmation est-elle simple que vous pouvez faire tout votre travail, sans connaître les bases telles que Bubble Trier , qu'il a essayé d'utiliser ci-dessus?


HMMM, mon hypothèse était qu'il souhaitait le tri de la liste basé sur le nombre d'occurrences de chaque numéro dans la matrice initiale, de sorte que la sortie souhaitée serait {2, 1, 1, 3, 3, 3, 0, 0, 0, 0, 0}.


@Edd Nous ne saurons jamais, jusqu'à ce que l'OP clarifie ...


@Bharathi: Pouvez-vous clarifier cette question s'il vous plaît?


23 Réponses :


2
votes

Si vous voulez juste Trier Le tableau, utilisez ce qui suit: xxx

Si vous voulez le trier manuellement, je vous recommanderais de lire Cette page , où vous pouvez trouver pseudo-code pour une variété d'algorithmes de tri.

Cependant, si vous êtes Recherche d'un moyen de trier le tableau basé sur le numéro Fréquence , je recommanderais Ceci < / a> page. Vous devriez inverser l'ordre de tri, Sonce que vous les souhaitez en ordre croissant.


0 commentaires

1
votes

Qu'en est-il de arrayes.sort (int []) ? De son Javadoc:

trie le tableau spécifié en ordre numérique croissant.


0 commentaires

1
votes
public static void main(String[] args) {
         int unsortedArray[] = {0,0,0,1,3,3,2,1,3,5,6,0};

         System.out.println("After sorting, the list elements are: "); //Just to show you it worked. :)
         bubbleSoprt(unsortedArray,unsortedArray.length);
         for(int i =0;i<unsortedArray.length;i++){
             System.out.print( unsortedArray[i] + " "); 
         }
     }

 private static void bubbleSoprt(int []unsortedarray,int lenght){
         int temp;
         for(int counter= 0 ;counter<lenght-1;counter++){
             for(int index = 0;index<lenght-1-counter;index++){
                 if(unsortedarray[index] > unsortedarray[index+1]){
                     temp = unsortedarray[index];
                     unsortedarray[index] = unsortedarray[index+1];
                     unsortedarray[index+1] = temp;
                 }
             }

         }

     }

0 commentaires

6
votes

Voici une approche pour vous démarrer pourrait être basée sur l'idée de tenir compte du nombre de fois que chaque entier dans la matrice initiale s'est produit sur une carte. Une fois que tous les nombres ont été comptés, triez la carte par ordre de valeur croissante, puis imprimez la sortie de la carte: xxx

qui utilise un comparateur Comparez les valeurs dans une carte : xxx


4 commentaires

Ce programme ne fonctionnera pas pour l'entrée lorsque la fréquence de deux nombre est identique. par exemple {5,2,8,8,5,5,8}. Essayez d'exécuter le code ci-dessus la sortie aura mal.


@Sumitrathi La définition de "travail" n'a jamais été vraiment clouée. D'après ce que je peux me rappeler, cette solution ignore complètement la valeur numérique et trie purement basé sur le nombre d'occurrences, de sorte que 2, 5, 5, 5, 8, 8, 8 est jugé valable que < Code> 2, 8, 8, 8, 5, 5, 5 . Il serait évidemment trivial d'ajouter un deuxième niveau de tri par valeur, si cela était souhaité.


Je ne parle pas du deuxième niveau de tri. Pour cette entrée particulière ({5,2,8,8,5,5,8}), votre programme donnera de la production à [2, 5, 5, 5]. Essayez de courir votre code contre cette entrée. Vous pouvez le vérifier.


Cela ne fonctionne pas pour de nombreuses intrants. J'ai essayé de le tester contre mon propre jeu de données et il n'a pas réussi à produire la production attendue.



0
votes

Le programme ci-dessous est peu long mais simple à comprendre. J'espère que c'est ce que vous attendiez.

import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.TreeMap;

public class Test {

    public static void main(String[] args) {

        int[] arra = {-2,-2,-2,-1,-1,-1,2,2,1,3,1,9,9,1,1,9,9};

        for(int i:sortedArrary(arra)){
            System.out.print(i+" ");
        }
    }

    static int[] sortedArrary(int[] inputArray)
    {
        TreeMap<Integer,Integer> repetitiveElements = null;

        if(inputArray==null || inputArray.length<=0)
            return null;

        repetitiveElements = new TreeMap<Integer,Integer>();
        for(int i=0;i<inputArray.length;i++)
        {
            if(repetitiveElements.containsKey(inputArray[i]))
            {
                repetitiveElements.put(inputArray[i], repetitiveElements.get(inputArray[i])+1);
            }else{
                repetitiveElements.put(inputArray[i],1);
            }
        }

        //System.out.println("repetitive "+repetitiveElements);


        ArrayList<Integer> keysArray = new ArrayList<Integer>(repetitiveElements.size());
        ArrayList<Integer> valuesArray = new ArrayList<Integer>(repetitiveElements.size());
        int key;
        Iterator<Integer> itr = repetitiveElements.keySet().iterator();
        while(itr.hasNext())
        {
            key = itr.next();
            keysArray.add(key);
            valuesArray.add(repetitiveElements.get(key));
        }

        /*
        System.out.println("keys "+keysArray);
        System.out.println("values "+valuesArray);
        */
        LinkedHashMap<Integer,Integer> map = new LinkedHashMap<Integer,Integer>();
        int maxValue=-1;
        int maxKey = -1;
        int pos = -1;

        for(int i=0;i<repetitiveElements.size();i++)
        {
            if(keysArray.get(i)==null)
                continue;

            maxKey = keysArray.get(i);
            maxValue = valuesArray.get(i);
            pos=i;
            for(int j=0;j<repetitiveElements.size();j++)
            {
                if(valuesArray.get(j)!=null && maxValue>valuesArray.get(j))
                {
                    maxValue = valuesArray.get(j);
                    maxKey = keysArray.get(j);
                    pos = j;
                }else if(valuesArray.get(j)!=null && maxValue==valuesArray.get(j)){
                    if(keysArray.get(j)!=null && maxKey>keysArray.get(j))
                    {
                        maxKey = keysArray.get(j);
                        pos = j;
                    }
                }
            }


            map.put(maxKey, maxValue);
            valuesArray.set(pos, null);
            keysArray.set(pos, null);

        }

        for(int i=0;i<keysArray.size();i++)
        {
            if(keysArray.get(i)!=null)
            {
                map.put(keysArray.get(i), valuesArray.get(i));
            }
        }
        itr = map.keySet().iterator();
        int count=0,value;
        while(itr.hasNext())
        {
            key = itr.next();
            value = map.get(key);

            for(int i=0;i<value;i++)
            {
                inputArray[count++] = key;
            }

        }
        return inputArray;
    }
}


0 commentaires

10
votes

Voici un moyen efficace de le faire à l'aide de Treemap.

import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

public class FrequencySort {
    public static void main(String[] args) {
        int[] ar = new int[] {5,2,8,8,5,5,8,1,9,0,1,1,0,1};

        Map<Integer,Integer> numbers = new HashMap<>();

        for(int number : ar) {
            if(numbers.containsKey(number)) {
                Integer  count = numbers.get(number);
                numbers.put(number, ++count);
            } else {
                numbers.put(number,1);
            }
        }

        final class FrequencyComparator implements Comparator<Integer> {
            Map<Integer,Integer> refMap;
            public FrequencyComparator(Map<Integer,Integer> base) {
                this.refMap = base;
            }

            @Override
            public int compare(Integer k1, Integer k2) {
                Integer val1 = refMap.get(k1);
                Integer val2 = refMap.get(k2);

                int num = val1.compareTo(val2)  ;
                // if frequencies are same then compare number itself
                return  num == 0 ? k1.compareTo(k2)   : num;
            }
        }

        FrequencyComparator comp = new FrequencyComparator(numbers);
        TreeMap<Integer,Integer> sortedMap = new TreeMap<Integer,Integer>(comp);
        sortedMap.putAll(numbers);
        for(Integer i : sortedMap.keySet()) {
            int frequencey = sortedMap.get(i);
            for(int count  = 1 ; count <= frequencey ; count++) {
                System.out.print(i + " " );
            }
        }
    }
}


0 commentaires

0
votes
import java.io.*;
import java.lang.*;
import java.util.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;

class SortingFrequency
{
    public static void main(String args[]) throws Exception{
        int i,j,temp,temp1,count;
        int []a=new int[10];
        int []freq=new int[10];
        Scanner s=new Scanner(System.in);
        for(i=0;i<5;i++){
           a[i]=s.nextInt();
           freq[i]=-1;
        }
        for(i=0;i<5;i++)
        {
            count=1;
            for(j=i+1;j<5;j++)
            {
                if(a[i]==a[j])
                {
                    count++;
                    freq[j]=0;
                }
            }
            if(freq[i]!=0)
            {
                freq[i]=count;
            }
        }
        Map map=new HashMap();
        for(i=0;i<5;i++){
            if(freq[i]!=0){
                map.put(a[i],freq[i]);
                System.out.println("map elt"+map);
                System.out.println("a"+a[i]+"fr"+freq[i]);
            }
        }
        Set<Entry<Integer,Integer>> set=map.entrySet();
        List<Entry<Integer, Integer>> list = new ArrayList<Entry<Integer, Integer>>(set);
        Collections.sort( list, new Comparator<Map.Entry<Integer, Integer>>()
        {
            public int compare( Map.Entry<Integer, Integer> o1, Map.Entry<Integer, Integer> o2 )
            {
                return (o2.getValue()).compareTo( o1.getValue() );
            }
        });
        for(Map.Entry<Integer, Integer> entry:list){
            System.out.println(entry.getKey()+" ==== "+entry.getValue());
        }
    }
}

1 commentaires

Veuillez formater la propriété de code et ajouter une explication à ce que le code fait et comment cela résout le problème.



1
votes

facile et optimisé. xxx


0 commentaires

0
votes
package problems;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

public class SortByFrequency {

    public static void main(String args[]) {
        int arr[] = { 2, 5, 2, 6, -1, 9999999, 5, 8, 8, 8 };
        Map<Integer, Integer> map = new HashMap<Integer, Integer>();
        int len = arr.length;
        for (int j = 0; j < len; j++) {
            if (map.get(arr[j]) == null) {
                map.put(arr[j], 1);
            } else {
                map.put(arr[j], (Integer) map.get(arr[j]) + 1);
            }
        }

        Set<Entry<Integer, Integer>> set = map.entrySet();
        ArrayList<Entry<Integer, Integer>> list = new ArrayList<Entry<Integer, Integer>>(set);
        list.sort(new Comparator<Entry<Integer, Integer>>() {
            @Override
            public int compare(Entry<Integer, Integer> o1, Entry<Integer, Integer> o2) {
                if (o1.getValue() < o2.getValue()) {
                    return 1;
                } else if (o1.getValue() > o2.getValue()) {
                    return -1;
                } else if (o1.getValue() == o2.getValue()) {
                    if (o1.getKey() < o2.getKey()) {
                        return 1;
                    } else {
                        return -1;
                    }
                }
                return 0;
            }
        });
        for (Map.Entry<Integer, Integer> en : list) {
            int val = en.getValue();
            while(val!=0){
            System.out.println(en.getKey());
            val--;          
            }
        }
    }

}

0 commentaires

0
votes
public class SortBasedOnFrequency {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String[] arr = new String[] { "abc", "def", "qas", "abc", "abc", "def" };

        new SortBasedOnFrequency().sort(arr);
    }

    void sort(String[] a) {
        Map<String, Integer> map = new HashMap<>();
        for (String s : a) {
//convert array to map putting key as the array element and value as the 
//number of occurence.
            map.put(s, map.get(s) == null ? 1 : map.get(s) + 1);
        }

    List<Map.Entry<String, Integer>> mapEntryList = new ArrayList<>map.entrySet());//  sort mapEntry list based on value
        Collections.sort(mapEntryList, new Comparator<Map.Entry<String, Integer>>() {

            @Override
            public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) {
                // TODO Auto-generated method stub
                return o1.getValue().compareTo(o2.getValue());
            }
        });
//print the object in sorting order of the occurrence.
        for (Entry<String, Integer> m : mapEntryList) {
            System.out.println(m.getKey() + " " + m.getValue());
        }
    }

}

1 commentaires

S'il vous plaît envisager d'ajouter une explication de texte de ce que le code fait.



0
votes

Je n'ai pas aimé les réponses ci-dessus, alors j'ajoute ce que j'ai fait. L'idée générale est assez simple - trier simplement la liste par comparateur code> qui prendra comme argument la carte de hachage.

2 5 6 1 1 3 3 3 0 0 0 0 


0 commentaires

-1
votes
import java.util.Arrays;
import java.util.Comparator;

public class TestString {
    public static void main(String[] args) {

        int arrTemp[] = { 2, 2, 2, 1, 1, 4, 5, 6, 6, 7, 7, 7, 7 };
        Arrays.sort(arrTemp);
        Integer[][] sortedArray = new Integer[6][2];
        int count = 0;
        sortedArray[count][0] = arrTemp[0];
        sortedArray[count][1] = 1;
        for (int i = 0; i < arrTemp.length - 1; i++) {
            for (int j = 1; j < arrTemp.length; j++) {
                if (arrTemp[i] == arrTemp[j]) {
                    sortedArray[count][1] = sortedArray[count][1] + 1;
                    i = j;
                } else {
                    ++count;
                    sortedArray[count][0] = arrTemp[j];
                    sortedArray[count][1] = 1;
                    i = j;
                }
            }
        }

        Arrays.sort(sortedArray, new Comparator<Integer[]>() {

            @Override
            public int compare(Integer[] o1, Integer[] o2) {
                return o1[1].compareTo(o2[1]);
            }
        });

        for (int row = 0; row < 6; row++) {
            for (int col = 0; col < sortedArray[row][1]; col++) {
                System.out.print(sortedArray[row][0] + " ");
            }
        }
    }
}

1 commentaires

Bien que ce code puisse répondre à la question, fournir des informations sur la manière et expliquer pourquoi il résout le problème améliore sa valeur à long terme.



0
votes

Utiliser simplement des tableaux. xxx


0 commentaires

2
votes

Utilisation de Treemap pour stocker l'élément en tant que clé, comptez les occurrences en tant que valeur, puis triez-la en fonction des valeurs. Java 8 flux rendez ci-dessous le code concis et simple à comprendre xxx


0 commentaires

0
votes
    public class Frequency {
        static int key;

        public static void main(String[] args) {
            Integer[] nums = { 7, 3, 4, 3, 4, 3, 4, 3, 6, 5, 7 };

            Map<Integer, Integer> m1;

//Convert the integer array into an Array List.
            ArrayList<Integer> numbers = new ArrayList<Integer>(Arrays.asList(nums));
    //ArrayList to store the number of occurences of numbers.
            List<Integer> values = new ArrayList<Integer>();
//ArrayList to show the array in requested order.
            List<Integer> output = new ArrayList<Integer>();

            m1 = new LinkedHashMap<Integer, Integer>();

            for (int a : numbers) {
    //Add data in Hash map where key is number and value is the total occurences of that number.
                if (m1.containsKey(a)) {
                    int value = m1.get(a);
                    m1.put(a, ++value);
                } else {
                    m1.put(a, 1);
                }
            }
            System.out.println(m1);
            for (Map.Entry<Integer, Integer> entry : m1.entrySet()) {
                values.add(entry.getValue());
            }

            Collections.sort(values, Collections.reverseOrder());
            System.out.println(values.toString());
            for (int m = 0; m < values.size(); m++) {
                for (Map.Entry<Integer, Integer> entry : m1.entrySet()) {
                    if (entry.getValue().equals(values.get(m))) {
                        key = entry.getKey();
                        System.out.println("Key is" + key);
                        for (int k = values.get(m); k > 0; k--) {
                            output.add(key);
                        }
                        break;
                    }

                }
                m1.remove(key);
            }
            System.out.println(output.toString());

        }
    }

1 commentaires

Plutôt que de fournir uniquement le code, veuillez également ajouter des commentaires ou une explication de votre code.



-1
votes

traits de tri bas basé sur la fréquence:

public static void main(String[] args) {
    int arr[] = { 2, 5, 2, 6, -1, 9999999, 5, 8, 8, 8 };
    Map<Integer, Integer> mp = new LinkedHashMap<>();
    List<Integer> res = new ArrayList<>();
    int count = 1;
    for (int i = 0; i < arr.length; i++) {
        if (!mp.containsKey(arr[i])) {
            mp.put(arr[i], count);
        } else {
            mp.put(arr[i], mp.get(arr[i]) + 1);
        }
    }
    if (!mp.containsValue(2)) {
        for (Integer ab : arr)
            res.add(ab);
        Collections.sort(res);
        Collections.reverse(res);
        System.out.println(res);
    } else {
        Set<Entry<Integer, Integer>> set = mp.entrySet();
        List<Entry<Integer, Integer>> list = new ArrayList<>(set);
        Collections.sort(list, new Comparator<Entry<Integer, Integer>>() {
            @Override
            public int compare(Entry<Integer, Integer> obj1, Entry<Integer, Integer> obj2) {
                if (obj2.getValue() > obj1.getValue())
                    return 1;
                if (obj2.getValue() < obj1.getValue())
                    return -1;
                else
                    return 0;
            }
        });
        for (Map.Entry<Integer, Integer> e : list) {
            for (int i = 1; i <= e.getValue(); i++)
                res.add(e.getKey());
        }
        System.out.println(res);

    }
}


0 commentaires

0
votes

Je suis un débutant à coder, j'ai essayé cela en utilisant "pour la boucle". Voici mon code -

//Driver Program
public static void main(String args[])
{
    int[] array = { 2, 2, 3, 4, 5, 12, 2, 3, 3, 3, 12 };
    sortByCount(array);
}

//Array element's count
static int elementsCount(int ar[], int n)
{
    int count = 0;
    for(int i : ar)
    {
        int max = n;
        if(i == max)
        {
            count++;
        }
        max = i;
    }
    return count;
}

//Ascending order sort by count 
static void sortByCount(int ar[])
{
    int temp = 0;
    for(int i = 0; i < ar.length; i++)
    {
        for(int j = i + 1; j < ar.length; j++)
        {
            if(elementsCount(ar, ar[i]) > elementsCount(ar, ar[j]))
            {
                temp = ar[i];
                 ar[i] = ar[j];
                 ar[j] = temp;
            }
        }   
    }
    printArray(ar);
}

//Print Array
static void printArray(int[] ar)
{
    for(int i : ar)
    {
        System.out.println(i);
    }
}   


0 commentaires

0
votes

Utilisation de la carte, de l'arrayage et du comparateur

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

public class OrderArrayFrequency {

public static void main(String[] args) {
    int nums[] = {0,0,0,1,3,3,2,1,3,5,6,0};
    ConcurrentHashMap<Integer, Integer> counts = new ConcurrentHashMap<Integer, Integer>();
    for (int i = 0; i < nums.length; i++) {
        if (counts.containsKey(nums[i])) {
            Integer c = counts.get(nums[i]) + 1;
            counts.put(nums[i], c);
        } else {
            counts.put(nums[i], 1);
        }
    }

    ArrayList<Integer> list = new ArrayList<>();

    for (Integer i : counts.keySet()) {
        list.add(counts.get(i));
    }

    Collections.sort(list, new Comparator<Integer>() {

        @Override
        public int compare(Integer o1, Integer o2) {

            if (o1 < o2)
                return -1;
            return 0;
        }
    });


    Set<Entry<Integer, Integer>> set = counts.entrySet();
    for (Integer i : list) {
        for (Entry<Integer, Integer> entry : set) {
            if (entry.getValue().equals(i)) {
                System.out.print(entry.getKey()+":"+entry.getValue()+ " ");
                counts.remove(entry.getKey());
            }
        }
    }
}
}


0 commentaires

0
votes
import java.util.*;
class SortArrayByFrequency 
{

    public static void main(String[] args) 
    {
        int a[]={2,2,2,2,4,4,4,4,4,4,5,6,6,6,6,6,1,1,1};
        int count=0;
        int k[]=new int[10];// for elements
        int v[]=new int[10];//store the frquency of corresponding element


        Map<Integer,Integer> map=new HashMap<>();

        for(int i=0;i<a.length;i++)
        {

            if(map.containsKey(a[i]))
            {
                map.put(a[i],map.get(a[i])+1);
            }
            else
            {
                map.put(a[i],1);
            }
        }
        Set<Integer> keys=map.keySet();
        int i=0,j=0;
        for(int key:keys){
            //System.out.println(key+" : "+map.get(key));
            v[i++]=map.get(key);
            k[j++]=key;
        }
        System.out.println("--------------------");

        //Sort the array which contains the frquency of elements
        for(int f=0;f<i-1;f++){
            //System.out.println(k[f]+" "+v[f]);
            int min=f;
            for(int g=f+1;g<i;g++)
            {
                if(v[min]>v[g])
                {
                    min=g;
                }
            }
            int temp=v[min];
            v[min]=v[f];
            v[f]=temp;
            //here we swap the element according to sorting ------------
            int temp1=k[min];
            k[min]=k[f];
            k[f]=temp1;
        }
        System.out.println("-----Array sort by frequency in ascending order------------");
        for(int l=0;l<i;l++){
            //System.out.println(v[l]+"    :: "+k[l]);
            for(int p=0;p<v[l];p++)
            System.out.print(k[l]+" ");
        }

    }
}
Ascending order
//OUTPUT: 5 1 1 1 2 2 2 2 6 6 6 6 6 4 4 4 4 4 4

0 commentaires

0
votes

Utilisation Java 8

Trier les éléments de matrice en fonction de ses fréquences P>

Hypothèses - B>

1. Triez le tableau en fonction de son occurrence naturelle dans un ordre croissant de
2. Si deux chiffres ont les mêmes fréquences, triez-les en fonction de la précédente numéro naturelle P>

Exemple B>: - [1, 1, 1, 1, 1, 2, 2 , 2, 3, 3, 3, 4, 4, 5] code>
sortie b>: - [5, 4, 4, 2, 2, 2, 3, 3, 3, 1, 1, 1, 1, 1] code> p>

solution b>: -
1 B>. Créer un haschmap qui stocke les éléments de tableau et ses occurrences de
2 B>. Mettez HASHMAP dans une liste où nous pouvons appliquer le tri en fonction de ses fréquences à l'aide d'un comparateur personnalisé
3 b>. La comparaison d'objet est Java: -
Si obj1 code> est inférieur à (code> obj2 code> puis retourner -1 code>
Si obj1 code> est égal à obj2 code> puis retourner 0 code>
Si obj1 code> est supérieur, alors obj2 puis retourner +1 code>
4 B>. Dans notre cas, si deux chiffres ont les mêmes fréquences, nous devrions mettre le numéro qui a une priorité naturelle dans la sortie de la production Ex: - Si ci-dessus exemple, numéro 2 code> et 3 code> survenu 3 code> est donc 2 code> devrait venir d'abord p >

public static void sortTheArrayByFrequency(int[] array){
    Map<Integer, Integer> map = new HashMap<>();

    //put array elements based on its frequncies
    for(int i : array){
        map.put(i, map.getOrDefault(i,0)+1);  
    }

    //Put the hashmap into a list where we use customized comparator
    List<Map.Entry<Integer, Integer>> list = new ArrayList<>();
    for(Map.Entry<Integer, Integer> e : map.entrySet()){
        list.add(e);
    }

    // list looks like [1=5, 2=3, 3=3, 4=2, 5=1]

    Collections.sort(list, (a, b) -> {
        // if its ouccrances are same then sort natually
        //else sort based on freqncies
        if(a.getValue() == b.getValue())
            return a.getKey() - b.getKey();
        else
            return a.getValue() - b.getValue();
    });

    // list looks like [5=1, 4=2, 2=3, 3=3, 1=5]

    for(Map.Entry<Integer, Integer> e : list){
        int num = e.getValue();
        while(num!=0){
            System.out.print(e.getKey()+ " ");
            num--;
        }
    }
}


0 commentaires

0
votes

Déjà il a été répondu mais il n'y a pas de bonne explication du code.So je vais essayer cela ici. Laissez le tableau à trier être: int [] array = {4,4,2,2,2,2,3,3,1,1,6,7,5} code>

Tout d'abord, comptez la fréquence de chaque numéro: p>

Pour le faire, nous allons créer une structure de données HASHMAP qui aura les éléments de tableau en tant que clé et leur fréquence comme valeur.et pour stocker notre sortie que nous aura une liste de sortie. P>

hashmap freqmap = nouveau hashmap (); code> p>

= nouvelle arrayliste (); code> p>

getordefault (clé, défaitValue) code>: Ceci est un moyen pratique de gérer le scénario où nous voulons une valeur renvoyée autre que null qui est renvoyé par obtenir la méthode chaque fois que la clé n'a pas été trouvée. p>

venant au code: p> xxx pré>

Nous avons maintenant des éléments cartographiés avec leur Fréquence dans HASHMAP. P>

class SortComparator implements Comparator<Integer>
{
    private final Map<Integer,Integer> freqMap;
    SortComparator(Map<Integer,Integer>freqMap)
    {
        this.freqMap = freqMap;
    }
    public int compare(Integer k1,Integer k2)
    {
    //Comparing by frequency
        int freqCompare = freqMap.get(k2).compareTo(freqMap.get(k1));
    //Comparing by value
        int valueCompare = k2.compareTo(k1);

        if(freqCompare == 0)//frequency of both k1 and k2 is same then
        {
            return valueCompare;
        }
        else 
        {
            return freqCompare;
        }
    }


0 commentaires

0
votes

// tri de la matrice dans une ordonnance décroissante sur la base de leurs fréquences.

import java.util.*;

class sorting {

static int x = 0;

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    int n = sc.nextInt();

    int a[] = new int[n];

    for(int i=0; i<n; i++){
        a[i] = sc.nextInt();
    }

    Arrays.sort(a);
    // l is number of distinct elements in array a.
    int l=1;
    for(int i=0; i<n-1; i++){
        if(a[i]!=a[i+1]){
            l++;
        }
    }

    // creating a 2d array from a 1d array having elements and their frequencies.
    int b[][] = new int[l][2];
    b[x][0] = a[0];
    int c=1;
    for(int i=1; i<n; i++){
        if(a[i]!=a[i-1]){
            b[x][1]=c;
            x++;
            c=1;
            b[x][0] = a[i];
        }
        else{
            c++;
        }

        if(i==n-1){
            b[x][1]=c;
        }
    }

    // sorting 2d array according their frequencies.
    for(int i=0; i<b.length; i++){
        for(int j=i; j<b.length; j++){
            if(b[i][1]<b[j][1]){
                int t = b[i][1];
                b[i][1] = b[j][1];
                b[j][1] = t;
                t = b[i][0];
                b[i][0] = b[j][0];
                b[j][0] = t;
            }
        }
    }

    for(int i=0; i<b.length; i++){
        int k=b[i][1];
        for(int j=0; j<k; j++){
            System.out.print(b[i][0]+" ");
        }
    }

}

// bubble sort.
public static void sort(int a[]) {
    int n = a.length;
    for(int i=0; i<n; i++){
        for(int j=i; j<n; j++){
            if(a[i]>a[j]){
                int t = a[i];
                a[i] = a[j];
                a[j] = t;
            }
        }
    }
}

}


0 commentaires

0
votes

Depuis Java 8, vous pouvez y parvenir avec une doublure one-liner (divisé en plusieurs lignes pour une meilleure lisibilité; -) xxx pré>

ou, si vous préférez un tableau de résultat p >

    int[] result = IntStream.of(numbers)
        .boxed()
        .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
        .entrySet()
        .stream()
        .sorted(Comparator.comparing(Map.Entry::getValue))
        .map(e -> Stream.generate(e::getKey).limit(e.getValue()))
        .flatMap(Function.identity())
        .mapToInt(Integer::intValue)
        .toArray();


0 commentaires