0

如何对 int[] 数组进行排序,我必须使用它还是可以只使用 java 的内置方法?

for (int x = 0; x < days.length - 1; w++) {
            for (short i = 0; i < days.length - 1; i++) {
                if (days[i].(days[i + 1]) > 0) {
                    days = days[i];

                    days[i] = days[i + 1];
                    days[i + 1] = days;


                }
            }
        }
4

2 回答 2

0

我写了一个片段来对一个简单的字符串数组进行排序。转载如下:

int length = winners.length;
        for(int i=0; i<length-1; i++){
            for(int j=0; j<length-i-1; j++){
                if(winners[j].compareTo(winners[j+1]) > 0){
                    //Swap the elements
                    String temp = winners[j];
                    winners[j] = winners[j+1];
                    winners[j+1] = temp;
                }
            }
        }

        for(String winner: winners){
            System.out.println(winner);
        }

这工作正常。如果要忽略大小写,可以使用 compareToIgnoreCase 方法。

于 2013-04-14T17:43:27.977 回答
0

对数组进行排序的最简单方法是Arrays.sort

    String[] array = {"c", "a", "b"};
    Arrays.sort(array);
    System.out.println(Arrays.toString(array));
    output -> [a, b, c]

    String[] array = {"2", "1", "3"};
    Arrays.sort(array);
    System.out.println(Arrays.toString(array));
    output -> [1, 2, 3]

同样的过程也适用于数组ints(或任何原语)

于 2013-04-15T15:17:40.710 回答