java - 数组排序后项目消失

标签 java arrays sorting

我最近学习了如何对整数数组进行升序排序。我正在尝试编写游戏,其中一部分涉及创建分层纹理渲染器;但是,当两个对象完全处于同一水平(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 数组。因此只保留最后一个匹配的索引。

如果对于给定的 yposvm 索引 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/

相关文章:

java.lang.NoClassDefFoundError : org/apache/axiom/om/OMNode

php - Mysqli 表用 thead 排序?

python - 如何根据对象的属性对对象列表进行排序?

php - 对数组进行排序,其中包含一些按天排序的日期,例如 php 中的星期日、星期一等

wpf - MVVM 分页和排序

Java 数组列表帮助

java - 如何在Android中将ArrayList存储到sharedPreferences中

Java Flight Recorder 以不同的文件格式导出?

c - 在 C 中,为什么不能在声明后将字符串分配给 char 数组?

java - 部分填充的数组 - 获取最小值和 toString