- tags: In-place
- WikiPedia: https://en.wikipedia.org/wiki/In-place%5Falgorithm
Let see two examples before we go further:
As above we can see, to reverse a array in-place, we just need swap each two elements in the array from both side to middle.
The pseudo code from WikiPedia:
function reverse_in_place(a[0..n-1])
for i from 0 to floor((n-2)/2)
tmp := a[i]
a[i] := a[n − 1 − i]
a[n − 1 − i] := tmp
The loop travels the array to the middle and swap each other in the list, two points we must be noticed:
- We stop the element at(not before):
floor((n - 2) / 2)
, It’s both1
of the two above figures. - We swap current element with
n - 1 - i
.