Inserting into a Sorted List

An algorithm for inserting an item into a list of numbers could be:
While place not found AND more places to look
  IF item > current element in list
    increment current place
  ELSE
    place found

Shift remainder of list down
Insert item
Increment length
If index is the place where item will be inserted, the algorithm for shifting the list down would be:
list[length]     = list[length - 1]
list[length - 1] = list[length - 2]
 . . .
list[index + 1]  = list[index]
In our code, we would use a For loop to implement the algorithm. A graphical view of this insertion method is here.

Previous page
Next page

Back to Index
Back to Outline