code: def head_sorted(lst, func=cmp, reversed=False):
      
      def make_maxhead(lst, start, end):
          root = start
          while True:
              left = root * 2 + 1
              right = root * 2 + 2
              if left > end:
                  break
              child = left
              if right <= end and func(lst[left], lst[right]) < 0:
                  child = right
              if func(lst[root], lst[child]) < 0:
                  lst[root], lst[child] = lst[child], lst[root]
                  root = child
              else:
                  break
      n = len(lst)
      for i in range(n, -1, -1):
          make_maxhead(lst, i, n-1)
      for end in range(n-1, -1, -1):
          lst[0], lst[end] = lst[end], lst[0]
          make_maxhead(lst, 0, end-1)
      return lst[::-1] if reversed else lst
docs: >>> l = [2,3,1,0,6,4,7,8,5,9]
      >>> head_sorted(l)
      [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
      >>> head_sorted(l, func=lambda a, b: cmp(b, a))
      [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
      >>> head_sorted(l, reversed=True)
      [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
      >>> head_sorted(l, func=lambda a, b: cmp(b, a), reversed=True)
      [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]