java - 交换二维数组元素

标签 java arrays sorting multidimensional-array

这是我的 FCFS 算法。

我有一个名为atst的二维数组,意思是到达时间,服务时间

数组大小为5*5

我的数组的逻辑图是这样的: enter image description here

第一列:进程名称

第二栏:到达时间

第三栏:服务时间(突发时间)

按到达时间(第二列)排序数组后,第四列和第五列将初始化等待时间和总时间。

我的问题是按第二列(到达时间)按升序对数组进行排序。

我的代码:

    // Sort array by arrival times
    int[] temp = new int[3];
    for (int i = 0; i < atst.length; i++) {
        if (atst[i][1] > atst[i + 1][1]) {     // Then swap!
            temp[i] = atst[i][1];
            atst[i][1] = atst[i + 1][1];
            atst[i + 1][1] = temp[i];
        }
    }

我使用 temp[3] 因为在排序之前其他列(第四和第五)都是空的(零)。

但是这段代码在这一行中产生了arrayOutOfBoundException:temp[i] = atst[i][1];

如何解决这个问题?

最佳答案

给你:

 // Sort array by arrival times
int[] temp = new int[atst.length]; //to avoid any out of bound.
for (int i = 0; i < atst.length-1; i++) { //-1 will solve
    if (atst[i][1] > atst[i + 1][1]) {     // Then swap!
        temp[i] = atst[i][1];
        atst[i][1] = atst[i + 1][1];
        atst[i + 1][1] = temp[i];
    }
}

希望这会起作用。对于 i 的最后一个值,您已经超出了 atst[i+1] 中的数组界限。这个-1将解决您的arrayOutOfBoundException问题。

编辑:试试这个:

 // Sort array by arrival times
int[] temp = new int[atst.length]; //to avoid any out of bound.
for (int i = 0; i < atst.length-1; i++) { //-1 will solve
    for (int j = 0; i < 2; j++) {
        if (atst[i][j] > atst[i + 1][j]) {     // Then swap!
           temp[i] = atst[i][j];
           atst[i][j] = atst[i + 1][j];
           atst[i + 1][j] = temp[i];
        }
    }
}

关于java - 交换二维数组元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22966195/

相关文章:

java - 实例化基类扩展时出现问题

python - numpy.logical_and 与乘法

javascript - 如何防止在数组中打印当前值(除了其他值)

objective-c - 如何对 NSMutableArray [ Objective-C ] 的整数值进行排序?

java - `setBufferedSize()`方法有什么作用?

java - 如何解决 Pane.setConstraints() 方法的不可见性

java - gRPC——在 Protobuf 中将 .png 图像从 Java 客户端发送到 Python 服务器

Javascript获取多维数组的键

algorithm - 这个问题和/或解决算法的正确名称是什么?

sorting - Delphi:存储TObjectList的多个排序