【发布时间】:2018-11-12 17:29:25
【问题描述】:
就最小化 gas 成本(或任何其他相关基准)而言,Solidity 中对一组值进行排序并找到最高分数的最佳方法是什么?如果重要的话,这些数字都在一个相当小的范围内
【问题讨论】:
标签: blockchain ethereum solidity
就最小化 gas 成本(或任何其他相关基准)而言,Solidity 中对一组值进行排序并找到最高分数的最佳方法是什么?如果重要的话,这些数字都在一个相当小的范围内
【问题讨论】:
标签: blockchain ethereum solidity
我不知道是否有最好的方法,但我通常会在您在数组上添加新元素时跟踪最高数字
function refreshTopXOrdered(uint value) private {
uint i = 0;
/** get the index of the current max element **/
for(i; i < topElementsOrdered.length; i++) {
if(topElementsOrdered[i] < value) {
break;
}
}
/** shift the array of one position (getting rid of the last element) **/
for(uint j = topElementsOrdered.length - 1; j > i; j--) {
topElementsOrdered[j] = topElementsOrdered[j - 1];
}
/** update the new max element **/
topElementsOrdered[i] = value;
}
其中 topElementsOrdered 只是一个具有预定义大小的数组:
uint[3] public topElementsOrdered; //can be any size
这将在您添加元素并保持顶部元素有序(降序)时跟踪更改。
假设是这样调用的
uint[] elements;
function add(uint value) public {
elements.push(value);
refreshTopXOrdered(value);
}
【讨论】:
如果您希望保留前几名,mirg 的方法是最好的方法。显然,如果您需要对所有元素进行排序,那么这种方法将不是最有效的方法,尤其是当数组变得更长时。
一般来说,您应该避免在区块链上进行排序。这将非常昂贵,并且随着阵列的大小变大,您可能会遇到气体不足的异常。如果你必须在链上排序,你可能想使用heapsort。
【讨论】: