Javascript Freecodecamp Algorithm #32: Implement Selection Sort

preview_player
Показать описание
Learn how to solve freecodecamp javascript algorithms in various ways! This series is up-to-date with all ES6 and beyond javascript notations

#javascript #algorithms #freecodecamp
Рекомендации по теме
Комментарии
Автор

Thank you for this awesome tutorial, Justin!!

GraceandWisdom
Автор

I wrote it this way, way less variables.

selectionSort = (array) => {
if(array.length === 0) return;
if(array.length === 1) return array;
for(let i=0; i < array.length; i++){
for(let j = i + 1; j < array.length;j++){
if(array[i] > array[j]){
[array[i], [array[j]]] = [array[j], [array[i]]]
}
}
}
return array;
}

console.log(selectionSort([1, 4, 2, 8, 345, 123, 43, 32, 5643, 63, 123, 43, 2, 55, 1, 234, 92]))

adamdreier
Автор

To make it a pure function don't you need a deep copy, not a shallow copy as you've said?

EDIT: it seems primitive data types are copied by value not reference when using slice, whereas objects are copied by reference and therefore would stop this from being a pure function!

kevin-johar
Автор

11:03, I was wondering how you are making changes to the arr variable when you're not specifying it... ? Specifically you're doing [arr[x], arr[x]] = [arr[x], arr[e]]. Aren't you supposed to reassign at least?

wonjaehwang
Автор

Hello Kim,
Hope you are doing great. I have understood the selection sort and I have managed to make it work by setting the min variable to the index rather than the actual value, however, I do not understand why the alternative approach which is what I came up with on my first try, does not work. If you have the time, please point out the mistake causing the following code to not work for selection sorting:


function selectionSort(array) {

for(var i = 0; i < array.length; i++){
var min = array[i];

for(var j = i+1; j < array.length; j++){
if(array[j] < min){
min = array[j];
}
}

var temp = array[i];
array[i] = min;
array[array.indexOf(min)] = temp;
}

return array;

}


console.log(selectionSort([5, 2, 6, 1, 10]));

nonipaify
Автор

heyy, what does j++/i++ stand for? ty for your answer

fra
Автор

terrible teaching, didnt learn anything

lolonoob