java - Using a break to get out of an enhanced for loop -
hi asked write following method homework , need clarification. want know if comparable item given parameter part of comparablelist array. assuming array sorted, told stop checking array if comparablelist has item in or if item smaller following item of array. used break not sure if break me out of enhanced loop avoid checking whole array if of conditions true. want make sure if there 50,000 items in array , find item @ position 5 stop checking rest of array. have never used break before not sure if me out of 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; }
the break
break out of loop, including enhanced one. solution work.
however, since returning find item, change loop return item found, or know not going 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 array sorted, linear search not best strategy: implementing binary search make algorithm faster.
Comments
Post a Comment