1.8 KiB
1.8 KiB
#алгоритмы #сортировка
Пройти по списку и найти наибольший элемент, этот элемент добавляется в новый список. Потом то же самое происходит со следующим элементом.
Вариант с циклом
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);
Вариант с рекурсией
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);
Источники:
