Let us take the following array and apply the Two Pointers Technique to reverse the array in-place.
{
"array": [6,3,8,2,7,4],
"showIndices": true,
"specialIndices": []
}
Pass 1
left = 0
, right = 5
Swap elements at left index and right index.
{
"array": [6,3,8,2,7,4],
"showIndices": true,
"highlightIndices": [0, 5],
"highlightIndicesGreen": [],
"specialIndices": [],
"labels": {
"0": "left",
"5": "right"
}
}
After swapping:
{
"array": [4,3,8,2,7,6],
"showIndices": true,
"highlightIndicesGreen": [0,5],
"labels": {
"0": "left",
"5": "right"
}
}
Increment left pointer by one, and decrement right pointer by one.
Pass 2
left = 1
, right = 4
Swap elements at left index and right index.
{
"array": [4,3,8,2,7,6],
"showIndices": true,
"highlightIndices": [1, 4],
"highlightIndicesGreen": [0,5],
"specialIndices": [],
"labels": {
"1": "left",
"4": "right"
}
}
After swapping:
{
"array": [4,7,8,2,3,6],
"showIndices": true,
"highlightIndicesGreen": [0,1,4,5],
"labels": {
"1": "left",
"4": "right"
}
}
Increment left pointer by one, and decrement right pointer by one.
Pass 3
left = 2
, right = 3
Swap elements at left index and right index.
{
"array": [4,7,8,2,3,6],
"showIndices": true,
"highlightIndices": [2, 3],
"highlightIndicesGreen": [0,1,4,5],
"specialIndices": [],
"labels": {
"2": "left",
"3": "right"
}
}
After swapping:
{
"array": [4,7,2,8,3,6],
"showIndices": true,
"highlightIndicesGreen": [0,1,2,3,4,5],
"labels": {
"2": "left",
"3": "right"
}
}
Increment left pointer by one, and decrement right pointer by one.
left = 3
, right = 2
left pointer crosses right pointer, end of loop.
Array is fully reversed.
{
"array": [4,7,2,8,3,6],
"showIndices": true,
"highlightIndicesGreen": [0,1,2,3,4,5],
"specialIndices": []
}