Is this considered a selection sort?

Viewed 43

I was practicing a while ago and came across selection sort. After some research across difference sources, there are some that declare an array then delete the current min location while others swap within the array

I tried to use ES6 for some trivial functions, did not use map since I wanted to understand the loop on a whiteboard.

Is this considered a selection sort?

selectionSortNoSwap = list)= => {
  const result = [];

  for (let i = 0; i < list; i++) {
    const min = Math.min(...list);
    const minIndex = list.indexOf(min);

    result.push(min);
    list.splice(minIndex, 1);
  }

  return result;
};

selectionSortNoSwap([3, 5, 2, 1, 4]);

Thank you

1 Answers

No. True selection sort sorts in-place, rather than creating another array. That is, given:

[3, 5, 2, 1, 4]

after the first iteration, a selection sort should produce the following data structure in memory:

[1, 5, 2, 3, 4]

where the 1 and 3 have been exchanged - and not

[3, 5, 2, 4]
[1]

If elements are not swapped with each other, it's not selection sort.

To sort in-place, you'd need something like

const selectionSort = (list) => {
  for (let i = 0; i < list.length; i++) {
    // for convenience - or use a for loop 
    const min = Math.min(...list.slice(i));
    const minIndex = list.indexOf(min, i);
    [list[i], list[minIndex]] = [list[minIndex], list[i]];
  }
  return list;
};

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

Related