Arrays | Linked lists | |
---|---|---|
Reading | O(1) | O(n) |
inserting | O(n) | O(1) (if not count search) |
Deletion | O(n) | O(1) (if not count search) |
Suppose you have a bunch of music on your computer. For each artist, you have a play count. and you want to sort this list from most to least played.
To go throuh each item, take O(n). doing it n times. so the time complexity is O(n^2)
// time: O(n^2n => n^2)
function selectionSort(array) {
const newArray = [];
while(array.length) {
const smallestIndex = findSmallestIndex(array);
newArray.push(array[smallestIndex]);
array.splice(smallestIndex, 1);
}
return newArray;
}
function findSmallestIndex(array) {
let min = array[0];
let minIndex = 0;
for(let i =0; i<array.length;i++) {
if(array[i]<min) {
min = array[i];
minIndex = i;
}
}
return minIndex;
}