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

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

    // Print the sorted elements and return the count
    int count = 0;
    for (int i = 0; i < vec.size(); i++)
    {
        while (vec[i].second > 0)
        {
            cout << vec[i].first << " ";
            vec[i].second--;
            count++;
        }
    }
    cout << endl;

    return count;
}

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

    int count = Sortelementsbyfreq(arr, n);

    cout << "Number of elements in sorted array: " << count << endl;

    return 0;
}