diff --git a/02_selection_sort/javascript/01_selection_sort.js b/02_selection_sort/javascript/01_selection_sort.js index b1e37c6c..95dc88d5 100644 --- a/02_selection_sort/javascript/01_selection_sort.js +++ b/02_selection_sort/javascript/01_selection_sort.js @@ -1,35 +1,42 @@ 'use strict'; /** * Finds the index of the element with the smallest value in the array - * @param {Array} array Source array + * @param {Array} arr Source array * @returns {number} Index of the element with the smallest value */ -const findSmallest = (arr) => { +const findSmallestIndex = (arr) => { let [smallestElement] = arr; let smallestIndex = 0; + for (let i = 1; i < arr.length; i++) { const el = arr[i]; + if (el >= smallestElement) continue; + smallestElement = el; smallestIndex = i; } + return smallestIndex; }; /** * Sort array by increment - * @param {Array} array Source array + * @param {Array} arr Source array * @returns {Array} New sorted array */ const selectionSort = (arr) => { - const size = arr.length; - const result = new Array(size).fill(0); - for (let i = 0; i < size; i++) { - const smallestIndex = findSmallest(arr); - const [smallestElement] = arr.splice(smallestIndex, 1); - result[i] = smallestElement; + const sortedArray = []; + const copyArray = [...arr]; + + for (let i = 0; i < arr.length; i++) { + const smallestIndex = findSmallestIndex(copyArray); + const [smallestElement] = copyArray.splice(smallestIndex, 1); + + sortedArray.push(smallestElement); } - return result; + + return sortedArray; }; const sourceArray = [5, 3, 6, 2, 10];