我最近学习了如何对整数数组进行升序排序。我正在尝试编写游戏,其中一部分涉及创建分层纹理渲染器;但是,当两个对象完全处于同一水平(y 位置相同)时,其中一个对象会由于排序过程而消失。
这是为什么?这是我的代码:
public void sort() {
int i = 0;
while (i < yposCount) {
order[i] = ypos[i];
i++;
}
Arrays.sort(order);
int j = 0;
while (j < yposCount) {
int k = 0;
while (k < yposCount) {
if (order[j] == ypos[k]) {
finalOrder[j] = k;
}
k++;
}
j++;
}
}
最佳答案
Arrays.sort(order);
int j = 0;
while (j < yposCount) {
int k = 0;
while (k < yposCount) {
if (order[j] == ypos[k]) {
finalOrder[j] = k;
}
k++;
}
j++;
}
对于每个 ypos
值,由于您在找到匹配项后没有break;
,因此您总是写入匹配的每个索引 k
到索引 j
处的 finalOrder
数组。因此只保留最后一个匹配的索引。
如果对于给定的 ypos
值 v
有 m
索引 ypos[k] == v
,您将这些索引中最大的 m
次写入 finalOrder
并且剩余的 m-1
索引总是被覆盖。因此相应的对象没有记录在finalOrder
中。
要解决此问题,请在找到匹配且 order
的下一个元素等于当前元素时增加 j
索引。
Arrays.sort(order);
int j = 0;
while (j < yposCount) {
int k = 0;
while (k < yposCount) {
if (order[j] == ypos[k]) {
finalOrder[j] = k;
// Now, if the next `order` is equal, continue looking for that value
if ((j+1 < yposCount) && (order[j+1] == order[j])) {
// more of the same ypos values to come
j++;
} else {
// All these ypos values found, end inner loop
break;
}
}
k++;
}
j++;
}
关于java - 数组排序后项目消失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14105153/