0
$\begingroup$

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;
}
$\endgroup$
0
$\begingroup$

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).

$\endgroup$
  • 1
    $\begingroup$ Thank you very much for detailed answer, I wanted to vote up but it does not let me do it for low reputation! I just do "not" understand that if I am right with the assumption, why people down vote my post. $\endgroup$ – higraphs Feb 25 at 22:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.