Selection Sort Visualization
Selection Sort
Algorithm Explanation
Selection Sort is a simple sorting algorithm that repeatedly finds the minimum element from the unsorted part of the array and puts it at the beginning. The algorithm maintains two subarrays: the sorted subarray and the unsorted subarray. In each iteration, it finds the smallest element from the unsorted subarray and swaps it with the first element of the unsorted subarray.
Time Complexity:
- Best Case: O(n²) - even if the array is already sorted
- Average Case: O(n²)
- Worst Case: O(n²) - regardless of the array's initial order
Space Complexity: O(1)
Custom Input
Enter numbers separated by commas. Example: 5, 3, 8, 1, 2
Selection Sort Implementation
// Selection Sort Algorithm
function selectionSort(arr) {
const n = arr.length;
for (let i = 0; i < n; i++) {
// Find the minimum element in the unsorted array
let minIdx = i;
for (let j = i + 1; j < n; j++) {
if (arr[j] < arr[minIdx]) {
minIdx = j;
}
}
// Swap the found minimum element with the first element
if (minIdx !== i) {
[arr[i], arr[minIdx]] = [arr[minIdx], arr[i]];
}
}
return arr;
}