what is the reason behind opf returning the value -1 if the item is not found. Why -1 ?
& how to define time complexity ?
Some thing is not understood?
If the element is found in the array we can return the index at which it is found but if it is not present in the array then we have to return a number which cannot be an index of the array. So, we return -1 because index of array can never be negative. It is basically to denote the ‘false’ condition that the element could not be found. We cannot return ‘false’ since return type of the function would be ‘int’. You can return any negative integer, it is just a convention to return -1.
In simple words, time complexity can be said as number of iterations a program takes.
I will be explaining it in Big O notation. There is a section on Time complexity. So just understand the big O notation.
Example:
for(int i=0;i<n;i++){
System.out.println(i);
}
In the above example the complexity will be O(n) because the program is being executed n times.
Example 2:
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
System.out.println(i);
}
}
In the above example the complexity will be O(n^2) because the program is being executed n*n times.
N times for every i and i goes from 1 to N.
Hence N^2
I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.
On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.