Selection Sort (algorithm scripting)

Tell us what’s happening:
I’ve been slowly working through these problems and seen a particular piece of code several times. I kind of know what it does but was hoping someone might be able to explain it a little better

function swap(a, b, arr){
  let tmp = arr[a];
  arr[a] = arr[b];
  arr[b] = tmp;


Sure. It’s a little deceptive, though. Almost more an object thing than an array. But here’s the logic:

  • Given two index numbers and an array, this is a mechanism to exchange them.
  • First, store the element at the first index to a variable. This way we don’t lose it.
  • Next, move the array element at the second index into that first index position.
  • Last, that value we stuck in a variable? It replaces the old value at that second index.

Interestingly, if you call it with two property names and an object, like so:

. swap(“firstName”, “lastName”, studentRecordObject):

… It would still work.

1 Like

Cool, that explains a lot. Thanks!