book-notes

Chapter 4 - Quick sort

Divide & conquer (D&C)

Sum up numbers in a list

function sum(array) {
	if(!array.length) { // base case
	 return 0;
  }
  
  return array[0] + sum(array.slice(1)); // reduce problem size
}

Count the number of items in a list

  1. Base case: If array is empty, count is 0
  2. Reduce problem size: first item + count of the rest
function count(array){
	if(!array.length) { // base case
		return 0;
	}

  return 1 + count(array.slice(1)); // reduce problem size
}

Find the maximum number in a list

  1. Base case: if array has one element, that is the max
  2. Reduce problem size: compare first item to the max from the rest of the array
function findMax(array){
	if(array.length === 1) { // base case
		return array[0];
	}
   
  const subMax = findMax(array.slice(1)); // reduce problem size
	return array[0] > subMax ? array[0] : subMax;
}

Quick sort

Quick sort example

	quicksort([15,10]) + [33] + quicksort([])

Screen Shot 2022-07-11 at 3.27.37 PM.png

Inductive proofs

Big O revisited

Screen Shot 2022-07-11 at 3.29.06 PM.png

Merge sort vs quick sort

Average case vs worst case

Recap

What we can do