Let's find the second largest number in the array using a loop.
{
"array": [30,20,10,50,60,40],
"showIndices": true
}
Initialize max = -Infinity and secondMax = -Infinity.
Check index 0
Current element is 30. Compare with max = -Infinity and secondMax = -Infinity.
30 is greater than current max. Update: secondMax = -Infinity, max = 30.
{
"array": [30,20,10,50,60,40],
"showIndices": true,
"highlightIndices": [0],
"labels": {"0":"i"}
}
{
"array": [0,30,null],
"showIndices": false,
"highlightIndicesGreen": [1, 2],
"emptyCompIndices": [0],
"labels": { "1": "max", "2": "secondMax" }
}
Check index 1
Current element is 20. Compare with max = 30 and secondMax = -Infinity.
20 is greater than current secondMax and not equal to max. Update: secondMax = 20.
{
"array": [30,20,10,50,60,40],
"showIndices": true,
"highlightIndices": [1],
"labels": {"1":"i"}
}
{
"array": [0,30,20],
"showIndices": false,
"highlightIndicesGreen": [1, 2],
"emptyCompIndices": [0],
"labels": { "1": "max", "2": "secondMax" }
}
Check index 2
Current element is 10. Compare with max = 30 and secondMax = 20.
No update required.
{
"array": [30,20,10,50,60,40],
"showIndices": true,
"highlightIndices": [2],
"labels": {"2":"i"}
}
{
"array": [0,30,20],
"showIndices": false,
"highlightIndicesGreen": [1, 2],
"emptyCompIndices": [0],
"labels": { "1": "max", "2": "secondMax" }
}
Check index 3
Current element is 50. Compare with max = 30 and secondMax = 20.
50 is greater than current max. Update: secondMax = 30, max = 50.
{
"array": [30,20,10,50,60,40],
"showIndices": true,
"highlightIndices": [3],
"labels": {"3":"i"}
}
{
"array": [0,50,30],
"showIndices": false,
"highlightIndicesGreen": [1, 2],
"emptyCompIndices": [0],
"labels": { "1": "max", "2": "secondMax" }
}
Check index 4
Current element is 60. Compare with max = 50 and secondMax = 30.
60 is greater than current max. Update: secondMax = 50, max = 60.
{
"array": [30,20,10,50,60,40],
"showIndices": true,
"highlightIndices": [4],
"labels": {"4":"i"}
}
{
"array": [0,60,50],
"showIndices": false,
"highlightIndicesGreen": [1, 2],
"emptyCompIndices": [0],
"labels": { "1": "max", "2": "secondMax" }
}
Check index 5
Current element is 40. Compare with max = 60 and secondMax = 50.
No update required.
{
"array": [30,20,10,50,60,40],
"showIndices": true,
"highlightIndices": [5],
"labels": {"5":"i"}
}
{
"array": [0,60,50],
"showIndices": false,
"highlightIndicesGreen": [1, 2],
"emptyCompIndices": [0],
"labels": { "1": "max", "2": "secondMax" }
}
Final Result:
Second Largest Element = 50
{
"array": [30,20,10,50,60,40],
"showIndices": true,
"labels": {
"4": "max",
"3": "secondMax"
}
}
{
"array": [0,60,50],
"showIndices": false,
"highlightIndicesGreen": [1, 2],
"emptyCompIndices": [0],
"labels": { "1": "max", "2": "secondMax" }
}
Comments
Loading comments...