Base/Knowledges/IT/Алгоритмы/Сортировки/Сортировка выбором (Selection sort).md
2026-02-23 19:52:05 +03:00

1.8 KiB
Raw Blame History

#алгоритмы #сортировка

!1_5WXRN62ddiM_Gcf4GDdCZg.gif Эффективность O(n) = O(n^2)

Пройти по списку и найти наибольший элемент, этот элемент добавляется в новый список. Потом то же самое происходит со следующим элементом.

Вариант с циклом

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);

Источники: