开发者

refactor my array sorting function

So, how to make it more compact?

   public static boolean isDirectOrder( int[] data )
   {
      boolean answer = true;

      if ( ( data != null ) && ( data.length > 1 ) )
   开发者_运维百科   {
         int last = data[0];

         for (int i = 0; i < data.length; i++)
         {
            if ( last <= data[i] )
            {
               last = data[i];
            }
            else
            {
               answer = false;
               break;
            }
         }
      }

      return answer;
   }

maybe exist standard tools for same checking?


public static boolean isDirectOrder( int[] data )
{
    if (data != null)
        for (int i = 1; i < data.length; i++)
            if (data[i] < data[i - 1])
                return false;

    return true;
}


Maybe something like this (not tested).

public static boolean isDirectOrder( int[] data )
{
    if ((data != null))
    {
       for (int i = 1; i < data.length; i++)
       {
           if (data[i] <= data[i - 1])
               return false;
       }
    }
    return true;
}


class A {
  public static boolean isDirectedOrder(int[] d) {
    if (d == null) return true;
    for (int i = 0, l = d.length - 1; i < l; i ++) if (d[i] > d[i + 1]) return false;
    return true;
  }

  public static void main(String[] args) {
    System.out.println(isDirectedOrder(new int[] { 1, 2, 3, 4, 5, 6, 8, 10 }));
    System.out.println(isDirectedOrder(new int[] { 1 }));
    System.out.println(isDirectedOrder(new int[] { 3, 2, 5, 1, 5, 7 }));
  }
}


It looks pretty compact to me. You're trying to find if the array is already sorted. You could remove your braces for some if statements:

if ( last <= data[i] )
{
last = data[i];
}

could become

if ( last <= data[i] )
   last = data[i];


It is a bit unlogic to return true when data == null.

public static boolean isDirectOrder( int[] data )
{
    if (data == null)
         throw new NullPointerException("Array is null");
    for (int i = 1; i < data.length; ++i)
        if (data[i] < data[i - 1]) // When this one is smaller than the previous one.
            return false;

    return true;
}

And, in fact, the statement data.length will throw a NullPointerException as well:

public static boolean isDirectOrder( int[] data )
{
    for (int i = 1; i < data.length; ++i)
        if (data[i] < data[i - 1])
            return false;

    return true;
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜