Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add sorting function for memory arrays #3490

Closed
CodeSandwich opened this issue Jun 17, 2022 · 4 comments · Fixed by #4846
Closed

Add sorting function for memory arrays #3490

CodeSandwich opened this issue Jun 17, 2022 · 4 comments · Fixed by #4846

Comments

@CodeSandwich
Copy link
Contributor

CodeSandwich commented Jun 17, 2022

🧐 Motivation
On-chain sorting is a risky design choice, but for small data sizes it could be useful for some algorithms. I'm proposing sorting of memory arrays, NOT storage arrays, that would be prohibitively expensive.

📝 Details
This issue is basically a temperature check. The implementation of an in-memory binary heap already exists here, it's polished, optimized, benchmarked and tested. It only needs to be simplified and generalized for sorting uint256s instead of being a single-use heap for specialized user-defined types. If this issue gets a positive reception, I can do that work.

@frangio
Copy link
Contributor

frangio commented Jun 23, 2022

I think you're right that in-memory sorting for small bounded arrays could be acceptable and useful.

Do you have use cases in mind?

What sorting algorithm would you suggest? A binary heap isn't exactly sorting.

It would be nice to sort in place to avoid memory expansion costs.

@CodeSandwich
Copy link
Contributor Author

I don't have a particular use case in mind, I just thought that it may be useful for somebody as OZ is the unofficial Solidity std-lib 🤷

Binary heap is one loop away from being an in-place heapsort implementation, just keep popping values and append them at the end of the array where the heap lives. That's part of the work that needs to be done before submitting a complete PR.

@Amxx
Copy link
Collaborator

Amxx commented Jun 24, 2022

We can do an in place quick sort like this. One usecase we recently discovered is sorting leaves when doing a multi merkle proof verify

@CodeSandwich
Copy link
Contributor Author

That's a neat quicksort implementation! I can't wait to benchmark it against heapsort. Before I've implemented heapsort I was experimenting with quicksort too and the gas usage was much worse. My implementation could've been poor though 😅

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
3 participants