From cad619574d1f4edbeb9d42e3bf350683b30cb2a5 Mon Sep 17 00:00:00 2001 From: ZGennadiy <56154440+ZGennadiy@users.noreply.github.com> Date: Tue, 17 Mar 2020 10:24:44 +0300 Subject: [PATCH] Update selection sort ES6 Added copy values from original array, because it must be immutable. Without that after call selectionSort origin array will become empty. --- 02_selection_sort/ES6/01_selection_sort.js | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/02_selection_sort/ES6/01_selection_sort.js b/02_selection_sort/ES6/01_selection_sort.js index fcb6919..2de1581 100644 --- a/02_selection_sort/ES6/01_selection_sort.js +++ b/02_selection_sort/ES6/01_selection_sort.js @@ -19,17 +19,21 @@ const findSmallestIndex = (array) => { // 2. Sorts the array const selectionSort = (array) => { + //Copy values from array, because it must be immutable. Without that after call selectionSort origin array will become empty. + const sortingArray = [...array]; const sortedArray = []; - const length = array.length; + const length = sortingArray.length; for (let i = 0; i < length; i++) { // Finds the smallest element in the given array - const smallestIndex = findSmallestIndex(array); + const smallestIndex = findSmallestIndex(sortingArray); // Adds the smallest element to new array - sortedArray.push(array.splice(smallestIndex, 1)[0]); + sortedArray.push(sortingArray.splice(smallestIndex, 1)[0]); } return sortedArray; }; -console.log(selectionSort([5, 3, 6, 2, 10])); // [2, 3, 5, 6, 10] +const array = [5, 3, 6, 2, 10]; +console.log(selectionSort(array)); // [2, 3, 5, 6, 10] +console.log(array); // [5, 3, 6, 2, 10]