33B. Example: Sort a Linked List

Now that we have a function that inserts a value into a sorted linked list, we can write a nondestructive function that sorts a linked list using an algorithm called insertion sort.

It is easy to sort an empty list; do nothing. To sort a nonempty list x:T,

  1. Sort T, yielding sorted list S.
  2. Insert x (destructively) into S.
  3. Return the sorted list (S).
  List sort(ConstList L)
  {
    if(L == NULL)
    {
      return NULL;
    }
    else
    {
      List S = sort(tail(L));
      insert(head(L), S);
      return S;
    }
  }

Exercises

  1. Rewrite the definition of sort to use a loop instead of recursion. (Hint. insert each member of L into an initially empty list R.) Answer