Use inserted to place x exactly once

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 newListThe 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.
