i have seen a few days ago such problem
there is given two array find elements which are common of these array
one of the solution was sort big array and then use binary search algorithm
and also there is another algorithm- brute-force algorithm
for (int i=0;i<array1.length;i++){
for (int j=0;j<array2.length;j++){
if (array1[i]==array2[j]){
//code here
}
}
it’s complexity is O(array1.lengtharray2.length);
and i am interested the first method’s complexity is also same yes?
because we should sort array first and then use search method
binary search algorithm’s complexity is log_2(n) so it means that total time will be
array.lengthlog_2(n) and about sort?
please explain me which is better
An
O(M log N)solutionLet the length of
arr1beO(M), and the length ofarr2beO(N). The sort/binary search algorithm isO(M log N).The pseudocode is as follows:
O(M log N)is vastly better thanO(MN).A linear-time solution
There’s also a third way which is
O(M+N), using a set that has aO(1)insertion and test. A hash-based set meets this expectation.The pseudocode is as follows: