R
E
A
C
T
O
xamples
epeat
ode
pproach
ptimize
est
{Selection Sort}
The Question
The Algorithm
[5, 2, 7, 20, 1, -1]
[-1, 2, 7, 20, 1, 5]
[-1, 1, 7, 20, 2, 5]
[-1, 1, 2, 20, 7, 5]
[-1, 1, 2, 5, 7, 20]
The Solution
function selectionSort(array) {
// For each element in the array...
for (var i = 0; i < array.length; i++) {
var minVal = array[i];
var minIdx = i;
// look through every element beginning there...
for (var j = i + 1; j < array.length; j++) {
// and keep track of the lowest one.
if (array[j] < array[minIdx]) {
minVal = array[j];
minIdx = j;
}
}
// Swap the lowest value with the current element
array[minIdx] = array[i];
array[i] = minVal;
}
return array;
}
The Performance
How fast is it?
O(n^2) - for each item in the array, it takes time proportional to the number of items in the array
How much space does it take?
O(n) total, O(1) extra - it's in place, so you're only using constant space in addition to the initial array
What about other sorting algorithms?
What should the interviewee do?
1. Implement Selection Sort
2. Talk about time and space complexity (O(n) notation)
3. Ask them to talk about space and time complexities of any other sorts they can think of (ask specifically at least about mergeSort and maybe bubbleSort)
Conclusion
Selection Sort is actually a pretty bad sorting algorithm, since it takes n^2 time and there are a lot of better ones that can be done in n log(n) time
Reacto: Selection Sort
By gtelljohann
Reacto: Selection Sort
- 2,014