1
\$\begingroup\$

The task:

Given a list, sort it using this method: reverse(lst, i, j), which reverses lst from i to j.

My functional solution:

const reverse = (lst, i, j) => [...lst.slice(0, i), ...lst.slice(i, j + 1).reverse(), ...lst.slice(j + 1)];

console.log(reverse([0,1,2,3,4,5], 2, 4));

My imperative solution:

function reverse(lst, i, j) {
  const lstReversed = [];
  let x = j;
  for (let k = 0, len = lst.length; k < len; k++) {
    lstReversed.push(lst[k < i || k > j ? k : x--]);
  }
  return lstReversed;
}

console.log(reverse([0,1,2,3,4,5], 2, 4));

The algorithm using the reverse function:

let lst = [7,6,3,8,5,0,9,1,2,4];

const len = lst.length;
for (let x = 0; x < len; x++) {
  for (let y = 1; y < len; y++) {
    if (lst[y - 1] > lst[y]) { lst = reverse(lst, y - 1, y); }
  }
}

console.log(lst);
\$\endgroup\$
  • 1
    \$\begingroup\$ You are supposed to write an algorithm which sorts the list using a reverse function, you only created the reverse function.. \$\endgroup\$ – konijn Apr 6 at 15:13

Your Answer

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

Browse other questions tagged or ask your own question.