Audrey
Audrey

Reputation: 2238

how to write a cleaner comparison

Hi I'm not familiar with algorithm, so I'm asking help for this simple comparison. So I have two unsigned int arrays with size N. and I need to compare which one is bigger. How I compare is I start from the left element, and if A[i] is bigger than B[i], then A array > B array.if they are equal, I compare A[i+1] and B[i+1]. A brut force way to do so is:

BOOL checkArray(int[] A, int[] B) {
    for(i=0; i< N; i ++){ 
       if (A[i] > B[i]) {
           return TRUE;
       }else if (A[i] == B[i]) {
           continue;
       } else {  \\ A[i] < B[i]
           return FALSE;
       }
    }
}

Please advise if there's a better way to achieve this. Thanks a lot !!!

Upvotes: 0

Views: 99

Answers (3)

fixagon
fixagon

Reputation: 5566

basically its ok, but to follow the .NET comparison schema you should return an integer. Like that you can use it directly for sorting too if you ever need that

i would implement it like that:

public class StringArrayComparer : IComparer<String[]>
{
    #region IComparer<string[]> Members

    public int Compare(string[] x, string[] y)
    {
        if (x.Length != y.Length)
            throw new ArgumentException("The two arrays dont have same size");

        for (int i = 0; i < x.Length; i++)
        {
            int strComp = x[i].CompareTo(y[i]);
            if (strComp != 0)
                return strComp;
        }
        return 0;
    }

    #endregion
}

Upvotes: 0

Skizz
Skizz

Reputation: 71070

Look at the standard library's implementation of strcmp.

bool checkArray (int [] a, int [] b)
{
  int
     i = 0;

  while (i < N && a [i] == b [i])
  {
    ++i;
  }

  return i < N && a [i] > b [i]; // return false if arrays equal
  //return i >= N || a [i] > b [i]; // return true if arrays equal
}

Your example code, however, has a route out of the function that is undefined - that is, is all elements of A are equal to all elements of B.

Upvotes: 1

Petar Minchev
Petar Minchev

Reputation: 47373

This is a perfectly normal and valid way:) Nothing better than that.

Just be sure to return properly if all elements are equal.

Upvotes: 1

Related Questions