Clojure 字母的气泡排序
我想开发一个冒泡排序函数,将字母按字母顺序重新排序 到目前为止,这是我的代码Clojure 字母的气泡排序,clojure,bubble-sort,Clojure,Bubble Sort,我想开发一个冒泡排序函数,将字母按字母顺序重新排序 到目前为止,这是我的代码 (defn bubble [ys x] (if-let [y (peek ys)] (if (> y x) (conj (pop ys) x y) (conj ys x)) [x])) (defn bubble-sort [xs] (let [ys (reduce bubble [] xs)] (if (= xs ys) xs (r
(defn bubble [ys x]
(if-let [y (peek ys)]
(if (> y x)
(conj (pop ys) x y)
(conj ys x))
[x]))
(defn bubble-sort [xs]
(let [ys (reduce bubble [] xs)]
(if (= xs ys)
xs
(recur ys))))
我认为问题在于(if(>yx)
行上的>和(if(=xsys)
)行上的=。这使得它需要一个数字而不是一个字母
我可以更改此代码以使其适用于字母吗?您可以使用以下函数使比较更通用:
(defn bubble [ys x]
(if-let [y (peek ys)]
(if (neg? (compare x y))
(conj (pop ys) x y)
(conj ys x))
[x]))
(defn bubble-sort [xs]
(let [ys (reduce bubble [] xs)]
(if (= xs ys)
xs
(recur ys))))
(bubble-sort [\b \a \c \z \h])
=> [\a \b \c \h \z]
还可以考虑允许自定义比较器的可选参数。
谢谢帮助。