I am trying to find the minimum element in an array, and I've been asked to figure out the number of comparisons needed while using the naïve approach. So the code I've written is:
int findMin(int arr[], int size) {
int comparisons = 0;
int temp = arr[0];
for (int i = 1; i < size; i++) {
comparisons++;
if (arr[i] < temp) {
temp = arr[i];
}
}
return comparisons;
}
Doesn't this require n-1 comparisons in all cases? Because I'll have to check all elements from arr[1] to arr[arr_length-1], and best case/worst case doesn't come into play as I don't know if the element is minimum unless I encounter all the elements of the array atleast once. Thus, it always does n-1 comparisons to get to the minimum element right?
One of my friends says its going to be 2(n-2)+1 worst case and n-1 best case but I don't know how that is? Am I wrong or is something else going on here?