1

In the book 'Data structures and algorithms in java' the following Array search method code is provided:

{
    int j;
    for(j=0; j< nElems; j++)            // for each element,
        if( a[j].getLast().equals(searchName))  // found item?
             break;                       // exit loop before end
    if(j == nElems)                    // gone to end?
      return null;                    // yes, can't find it
    else
      return a[j];                    // no, found it
} 

I am trying to understand why there needs to be a if(j == nElems) check? Wouldn't the method work the same if it were written as:

{           
    int j;
    for(j=0; j <nElems; j++)               
      if( a[j].getLast().equals(searchName))      
         return a[j];              
    return null;
}
1
  • You could understand the code better if format it correctly. Commented Feb 19, 2013 at 12:06

3 Answers 3

1

it would :P You could declare the j inside the for to limit its scope as well.

In the first implementation what it do is check if it iterated over all elements and didn't find anything, because j was incremented until it is equal the the condition of stop of the for-loop. I.e., it didn't stop because of break, indicating that it found an element.

I prefer your solution because it's easier to read :)

Sign up to request clarification or add additional context in comments.

Comments

1

Yes, both of these ways are give the same result.

Comments

0

Well , j never equals to nElems so this condition (j==nElems) is not wrong BUT it's not Working . You can make it like this (j==nElems-1) but it's steal waste of code , So your algorithm is better than the first one .

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.