cointop-sh / cointop

A fast and lightweight interactive terminal based UI application for tracking cryptocurrencies 🚀
https://cointop.sh
Apache License 2.0
3.98k stars 311 forks source link

Sort is not stable when values are identical #231

Closed lyricnz closed 2 years ago

lyricnz commented 2 years ago

When a table is sorted by a column where multiple rows have the same value, the order is not stable or predictable.

Normally refresh is slow enough that you might not notice this, but attached video demonstrates this with refresh triggered by mouse-move (unrelated patch). Ignore the silly colors :) The flickering rows each have price 3.23

https://user-images.githubusercontent.com/122371/137608338-3af860f3-9d7a-4939-8540-84487103097a.mov

lyricnz commented 2 years ago

There are 10 uses of sort.Slice() in the codebase - a couple of them may be vulnerable to unstable sorting.

favorites.go

    sort.Slice(sliced, func(i, j int) bool {
        return sliced[i].MarketCap > sliced[j].MarketCap
    })

portfolio.go

    sort.Slice(sliced, func(i, j int) bool {
        return sliced[i].Balance > sliced[j].Balance
    })

sort.go

    sort.Slice(list[:], func(i, j int) bool { 
        // switch depending on sortBy
    })

The video above is the third one.

lyricnz commented 2 years ago

Code could be changed to sort.SliceStable() but this relies on the current order of the items being predictable. Sometimes this might not matter, or perhaps we need to pre-sort by Rank?