Greetings to all programmers!
I would like to present my method to search an unsorted array(of Integers/Strings) with less time complexity. Linear search method is commonly used for unsorted arrays that has a worst case time complexity of O(n).
I have modified the linear search conditions to also check the last element of array, thus reducing iterations. Please check out this code and provide your valuable feedback. Here the worst case time complexity for searching through the loop in O(n/2). [EDIT - Through answers, came to know that it is still O(n)]
for(int i=0, len=arr.length; i<len; i++){
if(arr[i].equals(somethingToFind) || arr[--len].equals(somethingToFind)){
System.out.println("Found");
break;
}
}
Also, we can modify the if statement to include more conditions like checking arr[i+1] along with arr[len-1] and increment i by 2 to reduce iterations. Just for example!
I would like to know if the above code has any performance improvement when compared to linear search. What's your thoughts? Thanks for your responses!
EDIT - Thank you so much for that brilliant responses! Yes, I thought that extra conditions would cost performance, but just wanted to clarify on it. Great responses given on the BigONotation and Time Complexity. Thank you! :-)