DSA implementing Selection sort
2 min readJun 15, 2026
I”m getting into DSA thought I’d share my solutions here on medum.
var arr = [3,6,5,7,11,13,12,2];Get Sami Samiuddin’s stories in your inbox
Join Medium for free to get updates from this writer.
console.log(arr);
var i = 0;
// Btw, not having length-1 kept this running infinitely for some reason..
// perhaps because we're doing o+1, which when o was undefined kept runing maybe cuz it equal to undefined+1 = 1
for(var o=0;o<=arr.length;o++) {
var s = arr[o];
var sInd = o;
if(arr[o] == undefined) {
break; // This is important bit im adding right now..
// idk for some outer loop code keps running
//i think because we kept adding undefined value to outer array after it reached the final value (undefined) as length didn't have -1.
// So when it reached there, later in the code when we swap, we add undefined value to end of array
// this keps happening so code keeps running as it doesn't check for undefined.. simply having length-1 would work.
}
// Most important bit is that we store the smallest number in entire array compared to current value which we're comparing rest of the array values to, if we find a smaller number, we keep that in smallest var, if we find even smaller we store that one! in the end, we swap the smallest with curr number. then continue for next number.
for(i=o+1;i<=arr.length;i++) {
if(arr[i] < s) {
console.log('Curr smallest selection is ' + arr[i] + ' which is smaller than ' + s);
s = arr[i];
sInd = i;
}
}
// by this point we should have number that's smaller than s starting number in array.
console.log('Final smallest number in this iteration is ' + s);
console.log('****');
// finally we swap
var currOuter = arr[o];
arr[o] = s;
arr[sInd] = currOuter;
i++;
if(i==20) { // a way to stop infinite loop just in case, can be removed tho..!!
break;
}
}
console.log(arr);






