DEV Community

Discussion on: Sorting Algorithms in Javascript Part 2

jonrandy profile image
Jon Randy • Edited on

Wouldn't this be simpler?

const swap = (arr, a, b) => { [arr[a], arr[b]] = [arr[b], arr[a]] }

Better still, a version that doesn't mutate the original array:

const swap = (arr, a, b) => {
   let ret = [...arr];
   [ret[a], ret[b]] = [ret[b], ret[a]];
   return ret;

Also, your counting sort function both mutates and returns the original array whilst your bucket sort array returns a new array, leaving the original untouched (better). This code is somewhat confused - better to stick with either mutating variables or not, don't mix the two.

123jackcole profile image
Jack Cole Author

These are great suggestions! Thanks for taking the time to reply. Time to make some edits :)