Is the swap algorithm in this book correct?

64 Views Asked by At

I am reading the book on Algorithms: Design and Analysis, by Harsh Bhasin, and I doubt if I understand section "5.3.2 Reversing the Order of Elements of a Given Array", where it is written: "In order to reverse the order of elements of an array, the following procedure is employed.", but to me it does not seem that the given "procedure" ever changes anything, possibly what am I missing please?
This is the mentioned "procedure":

//temp is a temporary variable
//i is the counter
for(i=0; i<n; i++)
{
    temp = a[i];
    a [i] = a [n-i-1];
    a [n-i-1] = temp;
}

I came up with my own in JS as following, please tell me if I am correct:

let a = [1,2,3,4,5];
let limit = Math.ceil(a.length/2);
let a_length = a.length;
let temp;
for(let i=0;i<limit;i++){
  temp = a[i];
  a[i] = a[a_length-i-1];
  a[a_length-i-1] = temp;
}
1

There are 1 best solutions below

1
On BEST ANSWER

You are right, it should be i < n / 2 for the first loop, i.e. you should only perform the swaps on the first half of the array in order to reverse the array.

By the way, you can just use Math.floor rather than Math.ceil for the JS code, i.e. the index i just needs to be less than the floor of $n/2$. Using your ceiling version is still correct, but just does an unnecessary swap of the middle element with itself when $n$ is odd (e.g. if $n=3$ and the array is $[2,4,6]$, then using ceiling will swap the $4$ with itself, which is redundant).