Reversing a sub-array of an array in place →
In an earlier post, we saw how to reverse a given input array. But, it reversed the entire array. What if we want to pick a fragment of the input array and reverse only that?
Let us assume we are given the start
and end
indices - the window that we want to reverse. It is very similar to our previous approach, except that we need to be careful computing the indices to iterate on.
There is an interesting story about computation of mid-point given two window boundaries. At first glance, it would seem tempting to write it as (start + end) / 2
but it is safer (and more correct) to write it as start + ((end - start) / 2)
.