From 876731c7ef4699e8965e6831b9d17c5cb152ef61 Mon Sep 17 00:00:00 2001 From: "stanislaw.grin" Date: Sun, 20 Jul 2025 01:17:51 +0300 Subject: [PATCH] fix(javascript): prevent mutation of input array in selectionSort example --- .../javascript/01_selection_sort.js | 27 ++++++++++++------- 1 file changed, 17 insertions(+), 10 deletions(-) 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];