Loading...
A simple comparison-based algorithm that finds the minimum element in each pass and places it at the beginning. Easy to understand but inefficient for large datasets.
function selectionSort(arr) { const n = arr.length; // One by one move boundary of unsorted subarray for (let i = 0; i < n - 1; i++) { // Find the minimum element in remaining unsorted array let minIndex = i; for (let j = i + 1; j < n; j++) { if (arr[j] < arr[minIndex]) { minIndex = j; } } // Swap the found minimum element with the first element if (minIndex !== i) { [arr[i], arr[minIndex]] = [arr[minIndex], arr[i]]; } } return arr; } // Time Complexity: O(n²) - always // Space Complexity: O(1) - in-place // Comparisons: n(n-1)/2 // Swaps: O(n) - at most n-1 swaps
function selectionSortOptimized(arr) { let n = arr.length; for (let i = 0; i < Math.floor(n / 2); i++) { let minIndex = i; let maxIndex = i; // Find both min and max in one pass for (let j = i + 1; j < n - i; j++) { if (arr[j] < arr[minIndex]) { minIndex = j; } if (arr[j] > arr[maxIndex]) { maxIndex = j; } } // Place minimum at start [arr[i], arr[minIndex]] = [arr[minIndex], arr[i]]; // Adjust maxIndex if it was at position i if (maxIndex === i) { maxIndex = minIndex; } // Place maximum at end [arr[n - 1 - i], arr[maxIndex]] = [arr[maxIndex], arr[n - 1 - i]]; } return arr; }
function selectionSort(arr, compareFn) { const compare = compareFn || ((a, b) => a - b); const n = arr.length; for (let i = 0; i < n - 1; i++) { let extremeIndex = i; for (let j = i + 1; j < n; j++) { if (compare(arr[j], arr[extremeIndex]) < 0) { extremeIndex = j; } } if (extremeIndex !== i) { [arr[i], arr[extremeIndex]] = [arr[extremeIndex], arr[i]]; } } return arr; } // Usage examples: // selectionSort([3, 1, 4, 1, 5]); // ascending // selectionSort([3, 1, 4, 1, 5], (a, b) => b - a); // descending // selectionSort(objects, (a, b) => a.name.localeCompare(b.name));
Always performs n(n-1)/2 comparisons regardless of input order. No best or worst case - always quadratic.
In-place sorting algorithm using only a constant amount of additional memory space.
Best for small datasets or when memory is limited. Minimizes number of swaps.
Algorithm | Comparisons | Swaps | Stable | Adaptive |
---|---|---|---|---|
Selection Sort | O(n²) | O(n) | ❌ | ❌ |
Bubble Sort | O(n²) | O(n²) | ✅ | ✅ |
Insertion Sort | O(n²) | O(n²) | ✅ | ✅ |