#алгоритмы #сортировка ![[1_5WXRN62ddiM_Gcf4GDdCZg.gif]] Эффективность $O(n) = O(n^2)$ > Пройти по списку и найти наибольший элемент, этот элемент добавляется в новый список. Потом то же самое происходит со следующим элементом. ## Вариант с циклом ```javascript const findSmallestIndex = (arr) => { let smallestValue = arr[0]; let smallestIndex = 0; for (let i = 1; i < arr.length; i++) { const candidate = arr[i]; if (candidate < smallestValue) { smallestIndex = i; smallestValue = candidate } } return smallestIndex; } const selectionSort = (arr) => { const result = []; const copyArr = [...arr]; for (let i = 0; i < arr.length; i++) { const smallestIndex = findSmallestIndex(copyArr); const smallestValue = copyArr.splice(smallestIndex, 1)[0]; result.push(smallestValue); } return result; } const array = [2, 4, 5, 1, 6, 3]; const sorted = selectionSort(array); ``` ## Вариант с рекурсией ```javascript const findSmallestIndex = (arr) => { let smallestValue = arr[0]; let smallestIndex = 0; for (let i = 1; i < arr.length; i++) { const candidate = arr[i]; if (candidate < smallestValue) { smallestIndex = i; smallestValue = candidate } } return smallestIndex; } const recursiveSelectionSort = array => { if (!array.length) return []; const copyArr = [...array]; const smallestIndex = findSmallestIndex(copyArr); return [ ...copyArr.splice(smallestIndex, 1), ...recursiveSelectionSort(copyArr), ]; }; const array = [2, 4, 5, 1, 6, 3]; const sorted = recursiveSelectionSort(array); ``` Источники: - [[Адитья Бхаргава - Грокаем Алгоритмы]]