I wanted to implement a selection sort and wanted to make sure that I'm doing it correctly. I wanted to do it in a way that's efficient and use recursion. Please let me know if I am doing this correctly or if there is a better way for me to do it.
/** * selectionSort * @param toSort * @param sorted * @returns {Array} */ function selectionSort(toSort, sorted=[]) { if (!toSort.length) { return sorted; } let minIndex = findMinimum(toSort); sorted.push(...toSort.splice(minIndex, 1)) return selectionSort(toSort, sorted); } function findMinimum(arr) { let minIndex=0; arr.forEach(function (item, index) { if(item < arr[minIndex]) { minIndex = index; } }) return minIndex; } const testCase = [64, 25, 12, 22, 11] const answer = selectionSort(testCase);
for
loop is generally more efficient than.forEach()
as there's no function call and new scope involved. Probably best to usefor/of
.\$\endgroup\$for/of
also\$\endgroup\$