携带另一个元素并打印出来

瓷砖没有澄清我的问题,所以这是我的程序的一部分:


public static void selectionsort(int[] userID, double[] donation, PrintWriter output) {

    int min, swap;

    for (int i = 0; i < userID.length - 1; i++) {

        min = i;

        for (int m = i + 1; m < userID.length; m++) {

            if (userID[m] < userID[i]) {

                min = m;

                swap = userID[min];

                userID[min] = userID[i];

                userID[i] = swap;

            }

        }

        output.println(userID[i] + "   " + donation[i]);

    }

}

我的数组如下:


456             250.0

123            175.34

345            123.06

但是当我的方法去


output.println(userID[i]+"   "+donation[i]);

它打印出来是这样的:


123   250.0

345   175.34

456   123.06

我想保持身份证号码和捐款的匹配。例如,456 应该始终与 250.00 相关联,无论 456 移动到哪里。我如何解决它?


慕沐林林
浏览 75回答 1
1回答

蝴蝶刀刀

问题是因为在该方法中,只有userID数组被排序,而donation数组没有被相应地打乱。userID并且数组元素和数组元素之间没有其他映射donation,因此两个数组元素的打印都不会显示先前的关联。因此,在您的方法中,每当您交换userID数组元素的位置时,您还必须交换相应donation数组元素的位置。这可以如下完成:public static void selectionsort(int[] userID, double[] donation, PrintWriter output) {&nbsp; &nbsp; int min, swap;&nbsp; &nbsp; for (int i = 0; i < userID.length - 1; i++) {&nbsp; &nbsp; &nbsp; &nbsp; min = i;&nbsp; &nbsp; &nbsp; &nbsp; for (int m = i + 1; m < userID.length; m++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (userID[m] < userID[i]) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; min = m;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; swap = userID[min];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; userID[min] = userID[i];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; userID[i] = swap;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; swap=donation[min];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; donation[min]=donation[i];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; donation[i]=swap;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; output.println(userID[i] + "&nbsp; &nbsp;" + donation[i]);&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java