2.Selection Sort - Javascript

less than 1 minute read



const arr2 = [1,3,3,4,1,2];




var selectionSort = arr => {
    const len = arr.length;
    const swap = (arr,idx1,idx2)=>
    ([arr[idx1],arr[idx2]] = [arr[idx2],arr[idx1]]);

    for (let i = 0 ; i < len; i++){
        let idxOfMin = i;
        for(let j = i+1; j<len;j++){
            if(arr[j]<arr[idxOfMin]) idxOfMin=j;
        }
        if(idxOfMin!==i) swap(arr,idxOfMin,i);
    }
    return arr;
}

selectionSort(arr2)
console.log(arr2)





Leave a comment