Selection Sort in JavaScript

前端 未结 6 1063
轮回少年
轮回少年 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:13

    Eloquent solution:

    const selectionSort = (items) => {
      items.forEach((val, i, arr) => {
        const smallest = Math.min(...arr.slice(i))
        const smallestIdx = arr.indexOf(smallest)
    
        if (arr[i] > arr[smallestIdx]) {
          const temp = arr[i]
          arr[i] = arr[smallestIdx]
          arr[smallestIdx] = temp
        }
      })
    
      return items
    }
    

    Standard solution:

    const selectionSort = (arr) => {
      for (let i=0; i <= arr.length-1; i++) {
        // find the idnex of the smallest element
        let smallestIdx = i
    
        for (let j=i; j <= arr.length-1; j++) {
          if (arr[j] < arr[smallestIdx]) { 
            smallestIdx = j
          }
        }
    
        // if current iteration element isn't smallest swap it
        if (arr[i] > arr[smallestIdx]) {
          let temp = arr[i]
          arr[i] = arr[smallestIdx]
          arr[smallestIdx] = temp
        }
      }
    
      return arr
    }
    
    

    Testing:

    console.log( // [14, 29, 56, 72, 92, 98] 
      selectionSort([29, 72, 98, 14, 92, 56]) 
    )
    

提交回复
热议问题