# L-10 MCS 275 Wed 6 Feb 2008 : treesort.py
#
# We create a tree of lists to sort numbers.
# The tree is a recursive triple of triplets.

def Add(T,n):
    """
    Adds a number n to the triple of triples.
    All numbers less than T[1] are in T[0].
    All numbers greater than or equal to T[1]
    are in T[2].  Returns the new tree.
    """
    if len(T) == 0:
       return ( () , n , () )
    elif n < T[1]:
       return ( Add(T[0],n) , T[1] , T[2] )
    else:
       return ( T[0] , T[1] , Add(T[2],n) )

def Flatten(T):
    """
    T is a recursive triple of triplets.
    Returns a list of all numbers in T
    going first along the left of T, before
    the data at the node and the right of T.
    """
    if len(T) == 0:
       return []
    else:
       L = Flatten(T[0])
       L.append(T[1])
       L = L + Flatten(T[2])
       return L

def IsIn(T,n):
    """
    Returns True if n belongs to the tree,
    returns False otherwise.
    """
    if len(T) == 0:
       return False
    elif T[1] == n:
       return True
    elif n < T[1]:
       return IsIn(T[0],n)
    else:
       return IsIn(T[2],n)

def main():
   """
   Prompts the user for numbers and sorts
   using a tree: a triple of triplets.
   """
   T = ()
   while True:
      n = input('give number (-1 to stop) : ')
      if n < 0: break
      if IsIn(T,n):
         print n , 'is already in T'
      else:
         T = Add(T,n)
      print 'T =', T
   print 'sorted numbers =', Flatten(T)

main()
