Algorithm Steps
- Given an array of numbers
arr
. - Initialize
min_val
andsecond_min
toInfinity
. - Iterate through each element in the array.
- If the current element is less than
min_val
, updatesecond_min
tomin_val
, and then updatemin_val
. - Else if the current element is less than
second_min
and not equal tomin_val
, updatesecond_min
. - After the loop, return
second_min
.
Find Second Smallest using Loop - Optimal Approach Code
def find_second_smallest(arr):
min_val = float('inf')
second_min = float('inf')
for num in arr:
if num < min_val:
second_min = min_val
min_val = num
elif num < second_min and num != min_val:
second_min = num
return second_min
# Sample Input
arr = [30, 20, 10, 50, 60, 40]
print("Second Smallest:", find_second_smallest(arr))
Detailed Step by Step Example
Let's find the second smallest number in the array using a loop.
Initialize min = Infinity
and secondMin = Infinity
.
Check index 0
Current element is 30
. Compare with min = Infinity
and secondMin = Infinity
.
30 is smaller than current min. Update: secondMin = Infinity
, min = 30
.
Check index 1
Current element is 20
. Compare with min = 30
and secondMin = Infinity
.
20 is smaller than current min. Update: secondMin = 30
, min = 20
.
Check index 2
Current element is 10
. Compare with min = 20
and secondMin = 30
.
10 is smaller than current min. Update: secondMin = 20
, min = 10
.
Check index 3
Current element is 50
. Compare with min = 10
and secondMin = 20
.
No update required.
Check index 4
Current element is 60
. Compare with min = 10
and secondMin = 20
.
No update required.
Check index 5
Current element is 40
. Compare with min = 10
and secondMin = 20
.
No update required.
Final Result:
Second Smallest Element = 20