1
\$\begingroup\$

I made my own version of merge sort:

 (defn rsort[a]
 (cond 
 (<= (count a) 1) a
 :else 
 (let [half (/ (count a) 2) 
 [lh rh] (split-at half a)]
 (loop [res () slh (rsort lh) srh (rsort rh)]
 (cond 
 (empty? slh) (into srh res)
 (empty? srh) (into slh res)
 :else 
 (if (< (first slh) (first srh))
 (recur (cons (first slh) res) (rest slh) srh)
 (recur (cons (first srh) res) slh (rest srh))))))))

Any suggestion how improve this code?

Heslacher
50.8k5 gold badges83 silver badges177 bronze badges
asked Nov 20, 2015 at 12:19
\$\endgroup\$
3
  • \$\begingroup\$ Does this work with lists? Your usage if into makes me think it will only work with vectors. \$\endgroup\$ Commented Nov 20, 2015 at 14:23
  • \$\begingroup\$ Yeah, Its works for list and vectors as well. \$\endgroup\$ Commented Nov 20, 2015 at 14:30
  • 2
    \$\begingroup\$ Welcome to Code Review! I have rolled back the last edit. Please see what you may and may not do after receiving answers . \$\endgroup\$ Commented Nov 20, 2015 at 14:31

1 Answer 1

3
\$\begingroup\$

I tested with a couple of input values and for the most part, it seem fine. Note however, that the standard sort also works with e.g. [1 nil] (with output [nil 1]) whereas this code breaks with an exception during the comparison.

Code looks fine with a few minor issues:

  • The name should be merge-sort; rsort is not meaningful.
  • The values (first slh) and (first srh) are written down twice; the compiler might optimise that away, but IMO it would be nicer to have a separate let for them.
  • Emacs' clojure-mode indents the :else branch differently, dunno about that.

Some suggestions:

  • Support the same signature as the standard sort.
  • Add a docstring explaining the function.
  • Add tests, possibly with randomised input as well.
answered Nov 20, 2015 at 13:39
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.