code: def sort(in_bam, config, order="coordinate", out_dir=None):
      assert is_bam(in_bam), "%s in not a BAM file" % in_bam
      if bam_already_sorted(in_bam, config, order):
          return in_bam
      sort_stem = _get_sort_stem(in_bam, order, out_dir)
      sort_file = sort_stem + ".bam"
      if not utils.file_exists(sort_file):
          samtools = config_utils.get_program("samtools", config)
          cores = config["algorithm"].get("num_cores", 1)
          with file_transaction(config, sort_file) as tx_sort_file:
              tx_sort_stem = os.path.splitext(tx_sort_file)[0]
              tx_dir = utils.safe_makedir(os.path.dirname(tx_sort_file))
              order_flag = "-n" if order == "queryname" else ""
              resources = config_utils.get_resources("samtools", config)
              mem = config_utils.adjust_memory(resources.get("memory", "2G"),
                                               1.25, "decrease", out_modifier="M").upper()
              cmd = ("{samtools} sort -@ {cores} -m {mem} -O BAM {order_flag} "
                     "-T {tx_sort_stem}-sort -o {tx_sort_file} {in_bam}")
              do.run(cmd.format(**locals()), "Sort BAM file %s: %s to %s" %
                     (order, os.path.basename(in_bam), os.path.basename(sort_file)))
      return sort_file