SECTION 05 / 28

Handle empty, first and final insertion positions

1 min read
Check an empty list, a new smallest value and a new largest value. The picture’s plus sign means “insert”, not a valid list-concatenation expression.
Check an empty list, a new smallest value and a new largest value. The picture’s plus sign means “insert”, not a valid list-concatenation expression.

Three boundary cases test the algorithm. On [], the foreach body runs zero times, so a final fallback must produce [x]. If x is smaller than everything, insert before the first old element. If x is larger than or equal to every existing key under strict <, insert after the loop.

if NOT inserted:
    newList = newList ++ [x]
return newList

This final IF belongs outside the foreach loop. Putting it inside could insert too soon, or append x repeatedly. For a non-empty input, the output length must be old length + 1; for empty input it must be 1.

Try it yourself

What happens when you insert 5 into []?

Show explained answer

[5]. The final fallback appends it because the loop never ran.

Try it yourself

Where does 0 go in [1,3]?

Show explained answer

At the front: [0,1,3].

Try it yourself

Why is the final fallback still needed when most examples insert in the middle?

Show explained answer

It handles both empty input and values that belong after every old element.

YOUR STUDY PROGRESS

Finished this section? Save your progress.

Back to top ↑