字母冒泡排序

Bubble sort for letters

我想开发一个冒泡排序功能,可以将字母重新排序为正确的字母顺序。

到目前为止这是我的代码

(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 (> y x) 上的 > 和行 (if (= xs ys) 上的 =。这使得它需要一个数字而不是一个字母。

无论如何我可以更改此代码以使其适用于字母吗?

您可以使用 compare 函数使比较更普遍适用:

(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]

您还可以考虑允许自定义比较器的可选参数。