Write algorithm to find maximum element from array and find its best and worst case time complexity.
Algorithm to find maximum element -
start
arr[]
for (int i = 1; i < n; ++i) {
if (arr[0] < arr[i]) {
arr[0] = arr[i];
}
}
If the first element will be the largest element, then also loop will run till end of the array to verify.
and if the last element is the largest then also for loop will be executed till the end of the for loop.
So, the worst and best case both will be same that is "O(n)"
Comments
Leave a comment