Skip to content

Commit 0c8dc34

Browse files
authored
Merge pull request egonSchiele#161 from ZGennadiy/fix_es6_selection_sort
Update selection sort ES6 for keep original array immutable
2 parents cb4b1e7 + cad6195 commit 0c8dc34

File tree

1 file changed

+8
-4
lines changed

1 file changed

+8
-4
lines changed

02_selection_sort/ES6/01_selection_sort.js

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -19,17 +19,21 @@ const findSmallestIndex = (array) => {
1919

2020
// 2. Sorts the array
2121
const selectionSort = (array) => {
22+
//Copy values from array, because it must be immutable. Without that after call selectionSort origin array will become empty.
23+
const sortingArray = [...array];
2224
const sortedArray = [];
23-
const length = array.length;
25+
const length = sortingArray.length;
2426

2527
for (let i = 0; i < length; i++) {
2628
// Finds the smallest element in the given array
27-
const smallestIndex = findSmallestIndex(array);
29+
const smallestIndex = findSmallestIndex(sortingArray);
2830
// Adds the smallest element to new array
29-
sortedArray.push(array.splice(smallestIndex, 1)[0]);
31+
sortedArray.push(sortingArray.splice(smallestIndex, 1)[0]);
3032
}
3133

3234
return sortedArray;
3335
};
3436

35-
console.log(selectionSort([5, 3, 6, 2, 10])); // [2, 3, 5, 6, 10]
37+
const array = [5, 3, 6, 2, 10];
38+
console.log(selectionSort(array)); // [2, 3, 5, 6, 10]
39+
console.log(array); // [5, 3, 6, 2, 10]

0 commit comments

Comments
 (0)