book-notes

Chapter 2 - Selection Sort

Linked lists

Arrays

  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)

Selection sort

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.

  1. Go through the list, find the most-played, and add it to the new list
  2. Do it again to find the next-most-played, and add it to the new list
  3. Do it until the list is empty.

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;
}