开发者

isSorted method not working for all cases...not sure why

Here is the basic form of the question:

Write a method called isSorted that accepts an array of doubles as a parameter and returns true if they are sorted or false if they are not.

Here is my code:

public static boolean isSorted(double[] a){
   if (a.length == 1){
      return true;
   }
   boolean apples = false;
   int i = 1;
   while (i <= a.length-1){
      if (a[i] > a[i-1]){
         apples = true;
      } else {
         apples = false;
      }
      i++;
   }
   return apples;
}

when passed a double array {16.1, 12.3, 22.2, 14.4}, {1.5, 4.3, 7.0, 19.5, 25.1, 46.2}, or {42.0}, it returns false, true, true respectively开发者_如何学Go. However, when passed an array {1.5, 4.3, 7.0, 19.5, 7.8, 25.1, 46.2}, it returns true when it should return false.


Later cases of a[i] > a[i-1] (=> apples = true) are overwriting cases of apples being set to false. There's no need to keep iterating after you've found a single case where a[i] isn't less than a[i+1].

Other cleanup

  • This is a use case where a for loop is cleaner to use than a while loop.
  • You should handle empty arrays.
  • Assuming the array might contain repeated elements, you need to (correctly) handle the case where a[i] === a[i-1].

This method does all of the above:

public static boolean isSorted(double[] a){
    if (a.length < 2) return true;
    
    for (int i=1; i < a.length; i++) {
       if (a[i] < a[i-1]){
          return false;
       }
    }
    return true;
 }
 

Edit: oh, and why did you name the return variable apples? It doesn't make any sense in the context of the method, and hints at sloppy coding.


After assigning apples = false; in else, there is no need to iterate further. Just place break in else.


Almost good, I propose to add break:

  if (a[i] > a[i-1]){
     apples = true;
  } else {
     apples = false;
     break; // <--
  }


Your method is returning the result of the LAST comparison, as you don't exit when detecting an out-of-order condition.


When if false you have to break or return.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜