DEV Community

Discussion on: Selection Sort - Typescript

Collapse
 
aminnairi profile image
Amin • Edited

Maybe you could use relevant variables names with more than one character, this way complete beginners (we all have been there) can learn from your post some valuable knowledges and you target a larger audience.

Here is a proposal for you and others to better grasp the algorithm behind the selection sort.

const selectionSort = (numbers: number[]): number[] => {
  const {length} = numbers;

  for (let first = 0; first < (length - 1); first++) {
    let lowest = first;

    for (let second = (first + 1); second < length; second++) {
      if (numbers[second] < numbers[lowest]) {
        lowest = second;
      }
    }

    if (lowest !== first) {
      [numbers[first], numbers[lowest]] = [numbers[lowest], numbers[first]];
    }
  }

  return numbers;
}

const result = selectionSort([64, 25, 12, 22, 11]);

console.log(result);
Enter fullscreen mode Exit fullscreen mode