There are elsewhere good discussions on sorting of 5 things, which can be done with a maximum 7 comparisons.
It should be quicker to do what I want because we don’t care about the order of the 3 biggest integers (or the 2 smallest).
Context:
My program is playing the game Splendor, traversing the game tree as fast as possible. Just prior to the code below, it has populated the
var GemWeight = new int[5];
array to decide how important each of the five coloured gems are for procurement in the current state (the three highest weighted colors will be procured).
The elements are non-negative and no greater than 127.
I am presently finding the array indices (and respective integers) of the top 3 integers with this Linq:
var ThreeGemsWithIndices =
GemWeight
.Select((TotalWeight, ColorIndex) => new { v=TotalWeight, ColorIndex })
.OrderByDescending(x => x.v)
.Take(3)
.ToArray();
The Visual Studio profiler says my program is spending almost 20% of the time in this Linq, so it is ripe for attack.
What is the fastest c# algorithm to find the biggest 3 numbers, not necessarily sorted, and choosing the 3rd arbitrarily if there is a tie.
Eg: From array [2,6,10,43,6] we get an array or three variables containing 1,2,3 or 4,2,3 in any order.
[N.B.: Any suggestions on speeding up the Linq within the requirement of “Top 3 unordered” are welcome, although I suspect its speed will not match an imperative solution.]
2
Answers
Here two possible solutions are there
Code with simple sorting
Code with LINQ OrderByDescending
A more generic approach to be used is to go with LINQ based solution :