Selection Sort in JavaScript

前端 未结 6 1058
轮回少年
轮回少年 2020-12-18 11:05
function newsort(arr, left, right){    

for(var i= left; i < right; ++i){
    var min = i;
    for (var j = i; j < right; ++j){
        if (arr[min] > arr[         


        
6条回答
  •  温柔的废话
    2020-12-18 11:22

    The selection sort algorithm says: repeatedly find the minimum of the unsorted array.

    Recursive approach

    1. Find the minimum number and its index/position
    2. Remove the min item from the array and append it at the end of the same one
    3. After each iteration, when finding the minimum provide the unsorted array (if not you will again get the previous minimum). See argument of Math.min

    Note: the second argument of selectionSort (i) is needed in order to sort elements of the unsorted array

    function selectionSort(arr, i) {
      if (i === 0) {
        return arr;
      }
      const min = Math.min(...arr.filter((x, j) => j < i));
      const index = arr.findIndex(x => x === min);
      arr.splice(index, 1);
      arr.push(min);
      return selectionSort(arr, --i);
    }
    
    const unsortedArr = [5, 34, 5, 1, 6, 7, 9, 2, 100];
    console.log('result', selectionSort(unsortedArr , unsortedArr.length))

提交回复
热议问题