Coding Interview Prep: Algorithms - Implement Selection Sort (freeCodeCamp)

 Implement Selection Sort

Here we will implement selection sort. Selection sort works by selecting the minimum value in a list and swapping it with the first value in the list. It then starts at the second position, selects the smallest value in the remaining list, and swaps it with the second element. It continues iterating through the list and swapping elements until it reaches the end of the list. Now the list is sorted. Selection sort has quadratic time complexity in all cases.

Instructions: Write a function selectionSort which takes an array of integers as input and returns an array of these integers in sorted order from least to greatest.


Solution:


function selectionSort(array) {
  // Only change code below this line
  for (let i = 0i < array.length - 1i++) {
    let min = i;
    for (let j = i + 1j < array.lengthj++) {
      if (array[min] > array[j]) {
        min = j
      };
    }
    let temp = array[i];
    array[i] = array[min];
    array[min] = temp;
  }
  console.log(array)
  return array;
  // Only change code above this line
}


selectionSort([1428345123433256436312343255123492]);



Click here to go to the original link of the question.

Post a Comment

Previous Post Next Post