【发布时间】:2017-07-18 21:21:08
【问题描述】:
这个问题涉及我的算法以及它为什么不起作用。更具体地说,我想知道如何改进它来做我想做的事情。这就是它与建议的重复问题不同的原因。
我正在尝试创建一个函数,该函数根据它们都共享的属性值 (int) “indexFound”对对象数组进行排序。您可能会怀疑,我试图将 indexFound 较低的元素放在数组的开头。
function organizeTokens(list) {
for (i = 0; i < list.length - 1; i++) {
if (list[i].indexFound < list[i + 1].indexFound) {
// do nothing
} else if (list[i].indexFound > list[i + 1].indexFound) {
var tempVal = list[i];
list[i] = list[i + 1];
list[i + 1] = tempVal;
} else {
// should not happen unless we are comparing the same token
}
}
};
就目前而言,当我向它提供一组对象时,这段代码没有任何区别。这些元素仍然不是它们应该的顺序。我是否以正确的方式处理这个问题?我错过了什么明显的东西吗?
编辑:--------------------------------------------- ----------------------
示例输入:organizeTokens([{value: "if", indexFound: 7}, {value: "a", indexFound: 0}])
预期输出:[{value: "a", indexFound: 0}, {value: "if", indexFound: 7}]
实际输出:[{value: "if", indexFound: 7}, {value: "a", indexFound: 0}]
【问题讨论】:
-
你试过
Array.prototype.sort吗?还是您想自己通过算法解决这个问题? -
我没有。我现在将检查文档。我正在寻找最有效,最好是最简单的方法来做到这一点 - 因为它只是我正在构建的 Lexer 巨型机器中的一个小齿轮。
-
您能否发布一个输入数据示例、预期输出数据和您真正得到的输出数据?
-
当然。 @zer00ne 为您编辑了帖子,请查看。
标签: javascript arrays sorting