0

Hi everyone I was asked to write the following method for homework and I need some clarification. Basically I want to know if the Comparable item given as a parameter is part of the comparableList array. Assuming the array is sorted, I was told to stop checking the array if the comparableList has the item in it or if item is smaller than the following item of the array. I used break but I am not sure if break will get me out of the enhanced for loop to avoid checking the whole array if any of the conditions are true. I want to make sure that if there are 50,000 items in the array and I find the item at position 5 to stop checking the rest of the array. I have never used break before so I am not sure if it will get me out of the for loop.

public boolean contains(Comparable item) {

    Comparable[] comparableList= getStore();
    boolean isThere = false;
    for(Comparable p : comparableList)
    {
        if(item.compareTo(p)==0)
        {
            isThere = true;
            break;
        }
        if(item.compareTo(p)<0)
        {

            break;
        }

    }
    return isThere;
}
3
  • 1
    Did you try it? What happened? Commented Jul 17, 2013 at 20:03
  • 3
    Well did you try it? Yes, break will work - but you could have found that out for yourself. Or, preferrably (IMO) just return directly as soon as you know the answer - there's no need for the isThere variable. Commented Jul 17, 2013 at 20:04
  • The code is not complete I do not have a main method yet. I have write the main method at the end of the assignment, but I want to make sure this part is right. Commented Jul 17, 2013 at 20:04

2 Answers 2

6

The break will break out of any loop, including the enhanced one. Your solution will work.

However, since you are returning as soon as you find your item, you could change the loop to return as soon as the item is found, or as soon as you know that you are not going to find it:

Comparable[] comparableList= getStore();
for(Comparable p : comparableList) {
    if(item.compareTo(p)==0) {
        return true;
    }
    if(item.compareTo(p)<0) {
        return false;
    }
}
return false;

Moreover, since the array is sorted, linear search is not your best strategy: implementing Binary Search could make your algorithm significantly faster.

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

Comments

0

If you want to know the best way of stopping once it's found, just do this:

public boolean contains(Comparable item) {

Comparable[] comparableList= getStore();
    for(Comparable p : comparableList)
     {
        if(item.compareTo(p)==0)
        {
            return true;
        }
        if(item.compareTo(p)<0)
        {
         return false;
        }

    }
    return false;
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.