Selection Sort Visualizer
Interactive visualization of selection sort algorithm with step-by-step code execution
Array Visualization
Controls
Selection Sort Algorithm
1function selectionSort(array) {
2 const n = array.length;
3
4 // Outer loop for each position
5 for (let i = 0; i < n - 1; i++) {
6 // Find minimum element in remaining array
7 let minIndex = i;
8
9 // Inner loop to find minimum
10 for (let j = i + 1; j < n; j++) {
11 // Compare current element with minimum
12 if (array[j] < array[minIndex]) {
13 minIndex = j;
14 }
15 }
16
17 // Swap minimum element with first element
18 if (minIndex !== i) {
19 [array[i], array[minIndex]] = [array[minIndex], array[i]];
20 }
21 }
22
23 return array;
24}Get the length of the array
About Selection Sort
Understanding the fundamentals, properties, and complexity analysis of the selection sort algorithm
What is Selection Sort?
Selection Sort works by finding the minimum element from the unsorted portion and placing it at the beginning. It divides the array into sorted and unsorted portions, gradually building the sorted portion by selecting the smallest remaining element in each iteration.
Advantages
- Simple and intuitive algorithm
- In-place sorting (O(1) space)
- Minimum number of swaps (O(n))
- Good for small datasets
Disadvantages
- Poor time complexity O(n²)
- Not stable (relative order not preserved)
- No early termination possible
- Always makes O(n²) comparisons
Properties
When to Use
Small Arrays
Efficient for datasets with < 20 elements
Memory Constraints
When O(1) space complexity is required
Minimize Swaps
When swap operations are expensive
Educational Purposes
Teaching basic sorting concepts
Simple Implementation
When code simplicity is priority
Algorithm Steps
Find Minimum
Find the smallest element in unsorted portion
Swap to Position
Swap minimum with first unsorted element
Extend Sorted
Sorted portion grows by one element
Repeat Process
Continue with remaining unsorted elements
Complete Sort
Process until entire array is sorted