Steps:
Run the algorithm to see the recorded steps.
Steps:
Run the algorithm to see the recorded steps.
Selection Sort is a simple sorting algorithm that divides the array into two parts: a sorted part and an unsorted part. In each iteration, it scans the unsorted part to find the smallest element and swaps it with the first element of the unsorted part, effectively moving it to the sorted part. This process is repeated until the entire array is sorted.
Complexity: Unlike Bubble Sort and Insertion Sort, Selection Sort is not adaptive. It does not know if the list is already sorted and will always perform a complete scan. Therefore, its time complexity is O(n²) in all scenarios (worst, average, and best case). Its only significant advantage over the other two algorithms is the reduced number of swaps in memory (at most O(n) swaps). It is an in-place algorithm with O(1) space complexity.
1const selectionSort = (arr) => {
2 for (let i = 0; i < arr.length - 1; i++) {
3 let minIndex = i;
4
5 // Scan for the smallest element
6 for (let j = i + 1; j < arr.length; j++) {
7 if (arr[j] < arr[minIndex]) {
8 minIndex = j;
9 }
10 }
11
12 // If needed, swap it into position
13 if (minIndex !== i) {
14 [arr[i], arr[minIndex]] = [arr[minIndex], arr[i]];
15 }
16 }
17
18 return arr;
19};Selection Sort divides the list into two parts: a sorted part (on the left) and an unsorted part (on the right). On each iteration, it finds the smallest element in the unsorted part and moves it to the end of the sorted part. This process repeats until the entire list is sorted.
Like Bubble Sort, Selection Sort is rarely used in production due to its quadratic complexity. Its main advantage is performing the minimum possible number of swaps — at most N−1. This makes it useful in constrained hardware environments, such as flash memory (EEPROM), where each write operation consumes processing power and physically degrades the chip.