D
D
Denis Bredun2021-10-02 00:35:04
C++ / C#
Denis Bredun, 2021-10-02 00:35:04

How can you sort an array by the number of most repeated values?

For example, there is a sorted array array:
1
1
1
2
3
3
4
4
4
4
5
6
6
7
8
So here's how to sort the array by the number of most repeated values:
4
4
4
4
1
1
1
6
6
3
3
8
7
5
2

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ilya, 2021-10-02
@Luffy1

int[] array = {1, 1, 1, 2, 3, 3, 4, 4, 4, 4, 5, 6, 6, 7, 8};
var sortedByFrequency = array
    .GroupBy(o => o)
    .OrderByDescending(o => o.Count())
    .ThenByDescending(o => o.Key)
    .SelectMany(o => o)
    .ToArray();
Console.WriteLine(string.Join(",",sortedByFrequency.Select(o => o.ToString())));
//4,4,4,4,1,1,1,6,6,3,3,8,7,5,2

It if in one LINQ expression. If you need something very fast for large input arrays, then you should look for something else.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question