简体   繁体   English

从最低到最高对多维数组进行排序,只有第一个元素保持未排序状态

[英]Sorting a multidimensional array, lowest to highest, only the first element remains unsorted

I've been playing around with this problem, trying to sort out this multidimensional array but I keep on getting the wrong output. 我一直在处理这个问题,试图对这个多维数组进行排序,但是我一直得到错误的输出。 The array is sorted, except for the first element. 数组已排序,除了第一个元素。 Everything is in order, apart from the first element in the array. 除了数组中的第一个元素之外,其他所有东西都是有序的。 The first element in the sorted array, is also the first element in the array before it's sorted, which is sNamesLongitude[0][0] . 排序数组中的第一个元素,也是排序之前数组中的第一个元素,即sNamesLongitude [0] [0]。

The string sNamesLongitude[2][306] array has two rows. 字符串sNamesLongitude[2][306]数组有两行。 The first row holds the names of stations of the London underground, the second row holds its corresponding longitude. 第一行保存伦敦地下车站的名称,第二行保存其相应的经度。 I'm trying to sort out the array so the stations with the lowest value for its longitude comes first in the array, and the last value will have the highest value for its longitude, while keeping their corresponding name (row 1), together with its longitude. 我正在尝试对数组进行排序,以使其经度值最低的站点排在数组的首位,而最后一个值的经度值最高,同时保留其对应名称(第1行)以及它的经度。

String[][] temp = new String[2][1];
    for (int a = 0; a < sNamesLongitude[0].length - 1; a++) {

        if ((Double.parseDouble(sNamesLongitude[1][a])) > (Double.parseDouble(sNamesLongitude[1][a + 1]))) {

            temp[0][0] = sNamesLongitude[0][a];
            temp[1][0] = sNamesLongitude[1][a];

            sNamesLongitude[0][a] = sNamesLongitude[0][a + 1];
            sNamesLongitude[1][a] = sNamesLongitude[1][a + 1];

            sNamesLongitude[0][a + 1] = temp[0][0];
            sNamesLongitude[1][a + 1] = temp[1][0];
            a=0;
        }

The problem is temp only has two elements temp[0][0] and temp[1][0] 问题是temp只有两个元素temp[0][0]temp[1][0]

your code - 您的代码-

sNamesLongitude[0][a + 1] = temp[0][a]; // Gets exception

a might go up to values greater than 1 (to 306, as per your question), hence the exception occurs. a可能会上升到大于1值(根据您的问题达到306),因此发生异常。

After spending a whole day on it, the answer is: a should = -1, and not 0 at the end of the if block . 经过一整天后,答案是: a应该= -1,而if block的末尾不是0。

Can anyone please explain why though, is it something to do with scope? 任何人都可以解释为什么这与范围有关吗?

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

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