Let us take the following array and apply the logic to find the maximum and minimum elements.
{
"array": [6,3,8,2,7,4],
"showIndices": true,
"highlightIndices": [0]
}
{
"array": [0,6,6],
"showIndices": false,
"highlightIndicesGreen": [1, 2],
"emptyCompIndices": [0],
"labels": { "1": "max", "2": "min" }
}
Initialize max = 6
and min = 6
with the first element of the array.
Check index 1
Compare 3
at index=1 with current max = 6
and min = 6
.
3 is smaller than current min. Update min = 3
.
{
"array": [6,3,8,2,7,4],
"showIndices": true,
"highlightIndices": [1],
"specialIndices": [],
"labels": {"1":"i"}
}
{
"array": [0,6,3],
"showIndices": false,
"highlightIndicesGreen": [1, 2],
"emptyCompIndices": [0],
"labels": { "1": "max", "2": "min" }
}
Check index 2
Compare 8
at index=2 with current max = 6
and min = 3
.
8 is greater than current max. Update max = 8
.
{
"array": [6,3,8,2,7,4],
"showIndices": true,
"highlightIndices": [2],
"specialIndices": [],
"labels": {"2":"i"}
}
{
"array": [0,8,3],
"showIndices": false,
"highlightIndicesGreen": [1, 2],
"emptyCompIndices": [0],
"labels": { "1": "max", "2": "min" }
}
Check index 3
Compare 2
at index=3 with current max = 8
and min = 3
.
2 is smaller than current min. Update min = 2
.
{
"array": [6,3,8,2,7,4],
"showIndices": true,
"highlightIndices": [3],
"specialIndices": [],
"labels": {"3":"i"}
}
{
"array": [0,8,2],
"showIndices": false,
"highlightIndicesGreen": [1, 2],
"emptyCompIndices": [0],
"labels": { "1": "max", "2": "min" }
}
Check index 4
Compare 7
at index=4 with current max = 8
and min = 2
.
No update required.
{
"array": [6,3,8,2,7,4],
"showIndices": true,
"highlightIndices": [4],
"specialIndices": [],
"labels": {"4":"i"}
}
{
"array": [0,8,2],
"showIndices": false,
"highlightIndicesGreen": [1, 2],
"emptyCompIndices": [0],
"labels": { "1": "max", "2": "min" }
}
Check index 5
Compare 4
at index=5 with current max = 8
and min = 2
.
No update required.
{
"array": [6,3,8,2,7,4],
"showIndices": true,
"highlightIndices": [5],
"specialIndices": [],
"labels": {"5":"i"}
}
{
"array": [0,8,2],
"showIndices": false,
"highlightIndicesGreen": [1, 2],
"emptyCompIndices": [0],
"labels": { "1": "max", "2": "min" }
}
Final Result:
Maximum = 8
, Minimum = 2
{
"array": [6,3,8,2,7,4],
"showIndices": true,
"labels": {
"2": "max",
"3": "min"
},
"specialIndices": []
}
{
"array": [0,8,2],
"showIndices": false,
"highlightIndicesGreen": [1, 2],
"emptyCompIndices": [0],
"labels": { "1": "max", "2": "min" }
}