Answers for "selection sort javascript"

3

javascript selection sort

const selectionSort = array => {
  const arr = Array.from(array); // avoid side effects
  for (let i = 0; i < arr.length - 1; i++) {
    let minPos = i;
    for (let j = i + 1; j < arr.length; j++) {
      if (arr[j] < arr[minPos]) {
        minPos = j;
      }
    }
    if (i !== minPos) {
      [arr[i], arr[minPos]] = [arr[minPos], arr[i]];
    }
  }
  return arr;
};

console.log(selectionSort([4, 9, 2, 1, 5]));
Posted by: Guest on March-29-2021
0

selection sort javascript

let selectionSort = (arr) => {
    let len = arr.length;
    for (let i = 0; i < len; i++) {
        let min = i;
        for (let j = i + 1; j < len; j++) {
            if (arr[min] > arr[j]) {
                min = j;
            }
        }
        if (min !== i) {
            let tmp = arr[i];
            arr[i] = arr[min];
            arr[min] = tmp;
        }
    }
    return arr;
}
Posted by: Guest on September-04-2020

Code answers related to "Javascript"

Browse Popular Code Answers by Language