codebuddies / DailyAlgorithms

Do a problem. Create (or find) your problem in the issues. Paste a link to your solution. See others' solutions of the same problem.
12 stars 1 forks source link

[Practice] Selection Sort #31

Open lpatmo opened 5 years ago

lpatmo commented 5 years ago

Implement selection sort.

lpatmo commented 5 years ago

function selectionSort(input){
  //find smallest element
  //swap with first element (or put at beginning)
  //loop through rest of array
  //find smallest element again; then swap with first unsorted
  const swap = (arr, i,j) => {
    let temp = arr[i];
    arr[i] = arr[j];
    arr[j] = temp;
  }

  const findMin = function(index) {
    let minIndex = index;
    for (let i=index; i < input.length; i++) {
      if (input[i] < input[minIndex]) {
        minIndex = i;
      }
    }
    return minIndex;
  }
  for (let i = 0; i < input.length; i++) {
    swap(input, findMin(i), i)
  }
  return input;
}