Search code examples
nearprotocol

Best way to sort the TreeMap by values


My program needs to sort the TreeMap values. But values can be in 100,000. I am planning to use merge sort for it. How much gas/dollar will be required for the calculation? What will be the best and efficient way for finding N highest number? TreeMap has sorting by keys not value. https://docs.rs/near-sdk/2.0.0/near_sdk/collections/struct.TreeMap.html#method.iter_rev


Solution

  • Ignoring the blockchain part for now.

    If you need to have order on values in addition to the order on keys, you can use another data structure such as TreeSet<(Value, Key)> that uses tuples of Value and Key as a sorting key. When updating a TreeMap, you also update the TreeSet. To iterate on the values in the reverse order, you can use reverse iterator of the TreeSet. Having a pair instead of just a Value allows you to disambiguate the same values, but also having an associated Key for each value.

    Now to implement this on NEAR.

    Since we currently don't have TreeSet, you can just use another TreeMap<(Value, Key), ()>