Untitled

mail@pastecode.io avatar
unknown
plain_text
6 months ago
1.1 kB
4
Indexable
Never
#include <bits/stdc++.h>
using namespace std;

bool sortele(pair<int, int> a, pair<int, int> b)
{
    if (a.second == b.second)
        return a.first < b.first;
    return a.second > b.second;
}

vector<int> Sortelementsbyfreq(int arr[], int n)
{
    unordered_map<int, int> map;
    for (int i = 0; i < n; i++)
    {
        map[arr[i]]++;
    }
    vector<pair<int, int>> vec;
    for (auto it = map.begin(); it != map.end(); it++)
    {
        vec.push_back({it->first, it->second});
    }
    sort(vec.begin(), vec.end(), sortele);

    vector<int> result;
    for (int i = 0; i < vec.size(); i++)
    {
        while (vec[i].second > 0)
        {
            result.push_back(vec[i].first);
            vec[i].second--;
        }
    }

    return result;
}

int main()
{
    int arr[] = {4, 4, 5, 6, 4, 2, 2, 8, 5};
    int n = sizeof(arr) / sizeof(arr[0]);

    vector<int> sortedVec = Sortelementsbyfreq(arr, n);

    // Print the sorted vector
    for (int num : sortedVec)
    {
        cout << num << " ";
    }
    cout << endl;

    return 0;
}