【发布时间】:2018-06-12 09:19:23
【问题描述】:
需要根据私有变量值对一些芭蕾舞演员对象数组进行排序。我们可以对芭蕾舞演员对象或原始类型数组进行排序吗?有什么功能可以做到吗?
【问题讨论】:
标签: ballerina
需要根据私有变量值对一些芭蕾舞演员对象数组进行排序。我们可以对芭蕾舞演员对象或原始类型数组进行排序吗?有什么功能可以做到吗?
【问题讨论】:
标签: ballerina
目前没有内置的方法可以对数组进行排序。您可以根据需要实现排序功能。
在 github 中找到了一个可以重复使用的实现 - https://github.com/chamil321/ballerinaCentralWorkSpace/blob/master/sort/impl.bal。但它适用于整数。我认为它指的是https://central.ballerina.io/chamil/sort 包。你可以拉包试试看。
【讨论】:
int[] unsortedArray = [10, 15, 2, 5, 3, 0]; int[] result = sort:mergeSort(unsortedArray); github.com/chamil321/ballerinaCentralWorkSpace/blob/master/sort/…
Ballerina 现在似乎支持排序,但您必须完成所有繁重的工作。即使是简单的值类型。唉。
不管怎样,这里是一个“按字母顺序排序”的尝试,它包含 json 元素的数组,每个元素都有一个 name 元素 - obvs 也适用于简单的整数或字符串,或者经过一些调整的 woreva:
json items = [{ name: "aaa" }, { name: "aab" }];
items.sort(sortItems)
function sortItems(json a, json b) returns int {
// extract character by character numeric representation of string
int[] aname = a.name.toString().toCodePointInts();
int[] bname = b.name.toString().toCodePointInts();
// do character by character comparison
int i = 0;
while (i < aname.length() && i < bname.length()) {
if (aname[i] < bname[i]) { return -1; }
else if (aname[i] > bname[i]) { return 1; }
i += 1;
}
// if all the characters in the shared length is the same
// assume the shorter string should come first
if (aname.length() < bname.length()) { return -1; }
if (aname.length() > bname.length()) { return 1; }
return 0;
}
很高兴得到纠正,并且有一种更简单的本地方式来做到这一点。 (数组初始化可能是错误的,没有测试那个位,soz。)
【讨论】: