Create a Selection Sort Function in JavaScript

Share this video with your friends

Send Tweet

While not the fastest sorting algorithm, the selection sort function sorts an array by first creating a new array, calling a function that loops over a list and returns the location of the max/min element, and then pushes that returned indexed value into the newly created array. After the value is added it is then removed from the original list and the process continues until there is nothing left.

Elias Jr
Elias Jr
~ 6 years ago

would the splice also has some impact in this complexity ? as it take 0(n) time to delete the item, n * 2n = 2n^2 in the end still N^2 because we can drop 2, right ?

Thanks

Frantisek Musil
Frantisek Musil
~ 6 years ago

Shouldn't the second statement of the for loop inside the 'findLargestValue' function be 'i < list.length' instead of 'i <= list.length'? Even though it doesn't change the functionality, it seems to me like a bug.

Nick Llerandi
Nick Llerandi
~ 6 years ago

I thought returning 2 values from findLargestValue might make it a bit easier to read:

while (list.length) {
    let {largest, iOfLargest} = findLargestValue(list)
    sorted.push(largest)
    list.splice(iOfLargest, 1)
}
techtrainingAtshaadi
techtrainingAtshaadi
~ 5 years ago

renaming findLargestValue to findIndexOfLargestValue would be much clearer because that's what it does. It does not find the largest value in an array: just it's index.