繁体   English   中英

交换二维数组元素

[英]Swap two- dimensional array elements

这是我的FCFS算法。

我有一个名为atst二维数组意味着arrival time, service time

数组大小为5*5

我的数组的逻辑图片如下: 在此输入图像描述

第一列:流程名称

第二栏:到达时间

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

第四列和第五列将按照到达时间(第二列)排序等待时间和排序后的总时间。

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

我的代码:

    // 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]因为在排序之前其他列(第四和第五)是空的(零)。

但是这段代码在这一行中产生了arrayOutOfBoundExceptiontemp[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];
    }
}

希望这会奏效。 你已经超过结合的阵列atst[i+1]为的最后一个值i 这个-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];
        }
    }
}

您的设计在几个方面被打破。

首先,你根本不应该使用二维数组。 由于列具有不同的含义,因此包含命名字段的对象数组将为您节省大量工作。

其次,你所展示的并不接近排序算法。 即使在修复编码问题之后,对数组进行单次传递也不足以对其进行排序。 看看Arrays.sort()

第三,你的代码必须通过粗略的检查来打破。 变量i0迭代到atst.length - 1 然而你已经分配了只有3个职位的temp 除非atst.length确定不超过3,否则你将在范围错误的情况temp运行temp

第四,你想要排序行。 您尝试编写的代码将仅交换每行的第二列。 阵列的其余部分将保持原样。 我不认为这就是你想要的。

退后一步。 认为。 扔掉这个代码。 再试一次。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM