Reputation: 327
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;
}
Upvotes: 0
Views: 8179
Reputation: 726489
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.
Upvotes: 6
Reputation: 12611
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;
}
Upvotes: 0