DEV Community

Detacht
Detacht

Posted on

Selection SORT in JS

So as we all know selection sort has the following logic

From i=0 to < array length
Assume the element at i is the least in the array, assign i to indexOfMin
for J from i+1 to end of array
see if there is an element with lower value
if there is , record its index
if the endex of the current element and the index of the 'lowest' element is
is not the same swap em

I tried implementing this as follows (which was actually didnt work)

function selectionSort(array){
for(let i=0;i<array.length;i++){ //i= 0 , i< 3 i++,// processing when i =1,
let indexOfMin = i // assume indexofMin = 0, // indexOfmin = 1
let newIndexOfMin; //undef
console.log("iteration number in i " + i)//1
for(let j=i+1;j<array.length;j++){ ////j=1, j<3, ++2
console.log("iteration number in j " + j)
if (array[j]<array[indexOfMin]){ //2 <3 ,1<3
newIndexOfMin=j // j = 0
console.log("newIndexOfMin inside; " + newIndexOfMin)
}
}
console.log("newIndexOfMin; " + newIndexOfMin+ "\n")
if(newIndexOfMin!==indexOfMin){// 0 !=1
let newMinValue =array[newIndexOfMin]//
array[newIndexOfMin] = array[indexOfMin]
array[indexOfMin] = newMinValue;
console.log("print array here " + array )
}
}
return array;
}

And Iam still figuring this out, however meanwhile the correct answer is as below

function selectionSort(array){
for(i=0;i<array.length;i++){
let indexOfMin = i;
for(let j =i+1; j<array.length;j++){
if (array[j]<array[indexOfMin])
{ indexOfMin = j }
if(indexOfMin !=i){
let least= array[indexOfMin] ;
array[indexOfMin] = array[i];
array[i]= least;
}
}
}
return array;
}

Latest comments (0)