Drill 5: Explain each line — Sorting algorithms

Explain what each line of the example does.

Intermediate 5 min read Lesson 52 of 300 Challenge included
What you will be able to do
  • Explain what each line of the example does.

Practice task

Explain what each line of the example does.

sorts.jsJavaScript
function insertionSort(values) {
  const items = [...values]
  for (let i = 1; i < items.length; i++) {
    const current = items[i]
    let j = i - 1
    while (j >= 0 && items[j] > current) {
      items[j + 1] = items[j]
      j--
    }
    items[j + 1] = current
  }
  return items
}

function mergeSort(values) {
  if (values.length <= 1) return values
  const mid = Math.floor(values.length / 2)
  const left = mergeSort(values.slice(0, mid))
  const right = mergeSort(values.slice(mid))
  return merge(left, right)
}

function merge(left, right) {
  const result = []
  let i = 0
  let j = 0
  while (i < left.length && j < right.length) {
    if (left[i] <= right[j]) result.push(left[i++])
    else result.push(right[j++])
  }
  return result.concat(left.slice(i)).concat(right.slice(j))
}

const numbers = [5, 2, 9, 1, 5, 6]
console.log(insertionSort(numbers))
console.log(mergeSort(numbers))
console.log(numbers.sort((a, b) => a - b))
Your turn

Write your answer

Easy

Explain what each line of the example does.

TEXT · starter
Your answer…
Study tools

Make it yours.

Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.

Sign in to save notes and flashcards.Both are private to your account and stay with your progress.
Sign in
Finished reading?

Lock in what you just learned.

Mark this lesson complete to save your place and move one step closer to the certificate.

Lesson 52 of 300 · 0% of course