SECTION 06 / 28

Use inserted to place x exactly once

1 min read
inserted starts false and changes to true when x is placed. Original elements are copied on every iteration.
inserted starts false and changes to true when x is placed. Original elements are copied on every iteration.
Procedure SortedListInsert(L, x):
    newList = []
    inserted = false
    foreach z in L:
        if NOT inserted:
            if x < z:
                newList = newList ++ [x]
                inserted = true
        newList = newList ++ [z]
    if NOT inserted:
        newList = newList ++ [x]
    return newList

The flag remembers an event across loop iterations. Before insertion, test where x belongs. After insertion, stop testing x against new elements and just copy the remaining sequence. The line copying z is OUTSIDE the insertion IF, so every old element survives.

Use a new false flag for every procedure call. A true flag carried over from an earlier call would prevent insertion. The flag is a Boolean, the output is a list and x is an element; confusing these types changes the procedure.

Try it yourself

What if inserted is never set true after placing x?

Show explained answer

Later iterations can insert x again before other larger values.

Try it yourself

What if copying z is inside the insertion IF?

Show explained answer

Old elements that do not trigger insertion may vanish from the result.

Try it yourself

Does inserted = true mean the whole sort is finished?

Show explained answer

No. It only records that this one new item was placed during this insertion call.

YOUR STUDY PROGRESS

Finished this section? Save your progress.

Back to top ↑