Get byte order by value

I have an interesting thought-problem right now, so maybe some of you could help.

Basically, I have an array of bytes and I need to know the order of each individual element in this array - by value. Oh man, I’ll just show you a small example, I think this will help better:

byte[] array = new byte[4] { 42, 5, 17, 39 }

I want to get this as a result

4 1 2 3

What would be a smart way to do this?

In addition, I would like the algorithm to keep order if the values ​​are evaluated equal. So

new byte[4] { 22, 33, 33, 11 }

should lead to

2 3 4 1
+5
source share
2 answers

You can use:

byte[] byteArray = new byte[4] { 42, 5, 17, 39 };

var results = byteArray.Select((b, i) => new { Value = b, Index = i})
                    .OrderBy(p => p.Value)
                    .Select((p, i) => new { Index = p.Index, SortedPosition = i + 1 })
                    .OrderBy(p => p.Index)
                    .Select(p => p.SortedPosition);
+6
source
byte[] array = new byte[4] { 42, 5, 17, 39 }
var sorted = array.OrderBy(x=> x);

var result = from b in sorted 
    select (x => array.IndexOf(x) + 1);

As noted, this does not handle duplicates.

+3
source

All Articles