⬅ Previous Topic
Shell SortNext Topic ⮕
Find Second Largest in Array⬅ Previous Topic
Shell SortNext Topic ⮕
Find Second Largest in ArrayTopic Contents
Given an array of integers, your task is to find the maximum and minimum values present in the array using a simple loop (without any built-in functions).
If the array is empty
, there is no maximum or minimum, and the result should indicate that appropriately (e.g., null
or a message).
arr
.max_val
and min_val
with the first element of the array.max_val
, update max_val
.min_val
, update min_val
.max_val
and min_val
.def find_max_min_loop(arr):
max_val = arr[0]
min_val = arr[0]
for num in arr[1:]:
if num > max_val:
max_val = num
if num < min_val:
min_val = num
return max_val, min_val
# Sample Input
arr2 = [-5, -1, -9, 0, 3, 7]
max_val, min_val = find_max_min_loop(arr2)
print("Maximum:", max_val)
print("Minimum:", min_val)
Case | Time Complexity | Explanation |
---|---|---|
Best Case | O(n) | Even in the best case, every element must be checked to ensure no smaller or larger values exist. |
Average Case | O(n) | Each element is visited once to compare and possibly update the maximum or minimum. |
Average Case | O(n) | In the worst case, the loop still traverses the entire array to determine the max and min values. |
O(1)
Explanation: Only a fixed number of variables (e.g., max_val, min_val) are used, regardless of input size.
Let us take the following array and apply the logic to find the maximum and minimum elements.
Initialize max = 6
and min = 6
with the first element of the array.
Compare 3
at index=1 with current max = 6
and min = 6
.
3 is smaller than current min. Update min = 3
.
Compare 8
at index=2 with current max = 6
and min = 3
.
8 is greater than current max. Update max = 8
.
Compare 2
at index=3 with current max = 8
and min = 3
.
2 is smaller than current min. Update min = 2
.
Compare 7
at index=4 with current max = 8
and min = 2
.
No update required.
Compare 4
at index=5 with current max = 8
and min = 2
.
No update required.
Maximum = 8
, Minimum = 2
⬅ Previous Topic
Shell SortNext Topic ⮕
Find Second Largest in ArrayYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.