I was supposed to write a code that will say if an array has duplicates. The runtime wasn't important. I think my below code will have O(n²)
because I used a nested for-loop. I know there are much better and faster codes than the one I have written, but my question is if the break
statement I made inside the if-statement will make my code (a bit) faster? It should make it faster because the program knows "hey, we found a duplicate and we can stop searching for more". I once heard from a fellow student that the code is better / more stable if I avoid statements like return
or break
. Too bad I didn't care enough back then to ask why. Maybe you can tell me if this is true?
And if he is right and these statements "hurt" my code, there are any better workarounds?
public class FindDuplicate{
public static void main(String[] args){
int[] A={1,2,3,4,5,6,7,8,4};
boolean bool=false;
for(int i=0; i<A.length; i++){
for(int j=0; j<A.length; j++){
if(A[i]==A[j] && i!=j){
bool=true;
break;
}
}
}
if(bool==true){
System.out.print("Duplicate found");
}else{
System.out.print("No duplicate found");
}
}
}