Let's move all zeroes to the end while maintaining the order of non-zero elements.
{
"array": [0,1,0,3,12],
"showIndices": true
}
Initialize nonZeroIndex = 0
. We'll use this to track where the next non-zero element should go.
Check index 0
Element is 0
. It's zero. Do nothing and move to next.
{
"array": [0,1,0,3,12],
"showIndices": true,
"highlightIndices": [0],
"labels": { "0": "i", "-1": "nonZeroIndex" }
}
Check index 1
Element is 1
. It's non-zero, so move it to index 0
.
{
"array": [1,1,0,3,12],
"showIndices": true,
"highlightIndices": [1],
"labels": { "1": "i", "0": "nonZeroIndex" }
}
Check index 2
Element is 0
. It's zero. Do nothing and move to next.
{
"array": [1,1,0,3,12],
"showIndices": true,
"highlightIndices": [2],
"labels": { "2": "i", "0": "nonZeroIndex" }
}
Check index 3
Element is 3
. It's non-zero, so move it to index 1
.
{
"array": [1,3,0,3,12],
"showIndices": true,
"highlightIndices": [3],
"labels": { "3": "i", "1": "nonZeroIndex" }
}
Check index 4
Element is 12
. It's non-zero, so move it to index 2
.
{
"array": [1,3,12,3,12],
"showIndices": true,
"highlightIndices": [4],
"labels": { "4": "i", "2": "nonZeroIndex" }
}
Fill remaining positions with zeroes starting from index 3.
{
"array": [1,3,12,0,0],
"showIndices": true,
"labels": { "3": "start filling 0s" }
}
Final Result:
[1,3,12,0,0]