【问题标题】:What's wrong with my method that checks if an array of strings is sorted我检查字符串数组是否已排序的方法有什么问题
【发布时间】:2016-08-31 12:36:50
【问题描述】:

我正在做一个 Java 类,但我无法弄清楚我错在哪里。

我有一个名为 ArrayMethods 的类和一个必须用来查看我的数组是否已排序的方法。这是我的代码:

public class ArrayMethods
{
    String[] list; //instance variable
    /**
     * Constructor for objects of class ArrayMethods
     */
    public ArrayMethods(String[] list)
    {
        // initialise instance variables
        this.list = list;
    }

    /**
     * Determines if the array is sorted (do not sort)
     * When Strings are sorted, they are in alphabetical order
     * Use the compareTo method to determine which string comes first
     * You can look at the String compareTo method in the Java API
     * @return true if the array  is sorted else false.
     */
    public boolean isSorted()
    {
        boolean sorted = true;

        // TODO: Write the code to loop through the array and determine that each
        // successive element is larger than the one before it
        for (int i = 0; i < list.length - 1; i++){
            if (list[i].compareTo(list[i + 1]) < 0){
                sorted = true;
            }
        }
        return sorted;
    }
}

然后我有一个这样的数组测试器:

public class ArrayMethodsTester {
    public static void main(String[] args) {
        //set up
        String[] animals = {"ape", "dog", "zebra"};
        ArrayMethods zoo = new ArrayMethods(animals); 

        //test isSorted
        System.out.println(zoo.isSorted());
        System.out.println("Expected: true");

        String[] animals2 = {"ape", "dog", "zebra", "cat"};
        zoo = new ArrayMethods(animals2);         
        System.out.println(zoo.isSorted());
        System.out.println("Expected: false");

        String[] animals3 = {"cat", "ape", "dog", "zebra"};
        zoo = new ArrayMethods(animals3); ;
        System.out.println(zoo.isSorted());
        System.out.println("Expected: false");
    }
}

对于第一个数组,我确实得到了正确的结果,因为它是正常的,问题是我对其他 2 个得到了正确的结果,很明显这是错误的。我没有得到什么?

【问题讨论】:

标签: java arrays sorting arraylist


【解决方案1】:

可以通过在循环内直接返回false 使其更简单

   for (int i = 0; i < list.length - 1; i++) {
        if (list[i].compareTo(list[i + 1]) > 0) {
            return false;
        }
    }
    return true;

【讨论】:

    【解决方案2】:
    public class ArrayMethods
    {
        String[] list; //instance variable
        /**
         * Constructor for objects of class ArrayMethods
         */
        public ArrayMethods(String[] list)
        {
            // initialise instance variables
            this.list = list;
        }
    
        /**
         * Determines if the array is sorted (do not sort)
         * When Strings are sorted, they are in alphabetical order
         * Use the compareTo method to determine which string comes first
         * You can look at the String compareTo method in the Java API
         * @return true if the array  is sorted else false.
         */
        public boolean isSorted()
        {
            boolean sorted = true;
    
            // TODO: Write the code to loop through the array and determine that each
            // successive element is larger than the one before it
           for (int i = 0; i < list.length - 1; i++){
                if (list[i].compareTo(list[i + 1]) > 0){
                    sorted = false;
                    break;
    
                }
            }
            return sorted;
        }
    }`
    

    【讨论】:

      【解决方案3】:

      如果您喜欢 Java 8 流的语法,也可以使用它们(尽管这对它们来说不是一个完美的用例,因为您需要流的两个元素进行操作):

      public static boolean isSorted(final String[] array) {
          return !IntStream.range(1, array.length)
              .mapToObj(i -> new Pair<String>(array[i - 1], array[i])).parallel()
                  .anyMatch(t -> t.first.compareTo(t.second) > 0);
      }
      

      代码使用了一个小的帮助类Pair

      public static final class Pair<T> {
          final T first;
          final T second;
      
          private Pair(final T first, final T second) {
              this.first = first;
              this.second = second;
          }
      }
      

      此解决方案还可以并行运行,这将使其在大型阵列上运行时更快。

      感谢Collect successive pairs from a stream 使用流访问一对元素

      【讨论】:

      • 我很确定它可以处理重复条目并通过多次测试验证了这一点。你能举个例子来说明它不起作用的情况吗?
      • 啊,我明白了,你在这里使用否定......错过了。
      猜你喜欢
      • 2021-10-16
      • 2017-01-01
      • 1970-01-01
      • 2012-05-16
      • 2012-04-08
      • 1970-01-01
      • 1970-01-01
      • 2018-04-10
      • 1970-01-01
      相关资源
      最近更新 更多