Rudy’s OBTF Rudolf Adamkovič

Home / Computer science / Merge sort / Practice implementation


Phase 1: Split

(defun my-merge-sort-split (list)
  "Split LIST into halves.

Return a list containing two lists: a copy of first half of LIST and a
copy of the second half.  If LIST has an odd number of elements, the
first returned list is one element longer than the second.

This function implements the split phase of the merge sort algorithm."
  (let ((length (length list)))
    (pcase length
      (0 (list nil nil))
      (1 (list list nil))
      (_ (let ((half (/ length 2)))
           (list (take half list)
                 (drop half list)))))))
(ert-deftest my-merge-sort-split ()
  (should (equal (my-merge-sort-split '()) '(() ())))
  (should (equal (my-merge-sort-split '(1)) '((1) ())))
  (should (equal (my-merge-sort-split '(1 2)) '((1) (2))))
  (should (equal (my-merge-sort-split '(1 2 3)) '((1) (2 3))))
  (should (equal (my-merge-sort-split '(1 2 3 4)) '((1 2) (3 4)))))

© 2025 Rudolf Adamkovič under GNU General Public License version 3.
Made with Emacs and secret alien technologies of yesteryear.