Arrays - Selection Sort in DSA
Selection Sort is an in-place comparison sorting algorithm that divides the input list into two parts: the sublist of items already sorted and the sublist of items remaining to be sorted. It repeatedly finds the minimum element from the unsorted part and puts it at the beginning of the unsorted part. The algorithm maintains two subarrays in a given array. The subarray which is already sorted and the remaining subarray which is unsorted. In every iteration of selection sort, the minimum element from the unsorted subarray is picked and moved to the sorted subarray.
Algorithm
- The selection sort algorithm divides the input list into two parts: the sublist of items already sorted and the sublist of items remaining to be sorted.
- The algorithm repeatedly finds the minimum element from the unsorted part and puts it at the beginning of the unsorted part.
- The algorithm maintains two subarrays in a given array. The subarray which is already sorted and the remaining subarray which is unsorted.
- In every iteration of selection sort, the minimum element from the unsorted subarray is picked and moved to the sorted subarray.
- The array is sorted.
- Exit.
- The time complexity of the selection sort is O(n^2).
- The space complexity of the selection sort is O(1).
Pseudocode
Selection Sort
procedure selectionSort( A : list of sortable items )
n = length(A)
for i = 0 to n-1 inclusive do
min = i
for j = i+1 to n inclusive do
if A[j] < A[min] then
min = j
end if
end for
swap(A[i], A[min])
end for
end procedure
Diagram
Complexity
The time complexity of the selection sort is O(n^2). The space complexity of the selection sort is O(1).
Example
Selection Sort
function selectionSort(arr) {
let n = arr.length;
for (let i = 0; i < n - 1; i++) {
let min = i;
for (let j = i + 1; j < n; j++) {
if (arr[j] < arr[min]) {
min = j;
}
}
let temp = arr[i];
arr[i] = arr[min];
arr[min] = temp;
}
return arr;
}
const arr = [64, 25, 12, 22, 11];
console.log(selectionSort(arr)); // [11, 12, 22, 25, 64]