目前正在编程的bubblesort算法。我找到了某个网站的源代码:
Scanner sc = new Scanner(System.in);
System.out.println("Enter the size of the array which you would like to create: ");
应用程序现在所做的是,它接受用户的输入号。并制造一系列随机数。使用这个数组,它应用了Bubblesort算法。
现在,我正试图把这个翻译成Clojure。我知道用户输入可以通过以下功能来实现:
Flush
和
read-line
除此之外,我不明白如何获得所需数组大小的用户输入,然后创建一个随机数数组,然后应用冒泡排序。到目前为止,这就是我所拥有的(Bubblesort从rosetta网站上找到的):
(ns BubbleSort
(:import java.util.ArrayList)
(:import (java.util Date)))
(defn safe-println [& more]
(.write *out* (str (clojure.string/join " " more) "\n")))
; set a timestamp
(defn restart-profiling []
(def last-time-stamp (atom (System/nanoTime))
)
)
; get ms since last timestamp
(defn get-delta-ms []
(let [last @last-time-stamp
current (System/nanoTime)
ticks (- current last)
]
(restart-profiling)
(float (/ ticks 1000000)) ; calculate the delta in milliseconds
)
)
(defn bubble-sort
"Sort in-place.
arr must implement the Java List interface and should support
random access, e.g. an ArrayList."
([arr] (bubble-sort compare arr))
([cmp arr]
(letfn [(swap! [i j]
(let [t (.get arr i)]
(doto arr
(.set i (.get arr j))
(.set j t))))
(sorter [stop-i]
(let [changed (atom false)]
(doseq [i (range stop-i)]
(if (pos? (cmp (.get arr i) (.get arr (inc i))))
(do
(swap! i (inc i))
(reset! changed true))))
@changed))]
(doseq [stop-i (range (dec (.size arr)) -1 -1)
:while (sorter stop-i)])
arr)))
(restart-profiling)
(println (bubble-sort (ArrayList. [10 9 8 7 6 5 4 3 2 1
10 9 8 7 6 5 4 3 2 1
10 9 8 7 6 5 4 3 2 1
10 9 8 7 6 5 4 3 2 1
10 9 8 7 6 5 4 3 2 1
10 9 8 7 6 5 4 3 2 1
10 9 8 7 6 5 4 3 2 1
10 9 8 7 6 5 4 3 2 1
10 9 8 7 6 5 4 3 2 1
10 9 8 7 6 5 4 3 2 1
10 9 8 7 6 5 4 3 2 1
10 9 8 7 6 5 4 3 2 1
10 9 8 7 6
])))
(safe-println "The serial implementation "(get-delta-ms) "ms")
需要:
提前感谢!
编辑:
用户输入:
def(input
(println "Enter the size of the array: ")
)
println(read-line)
输入应该决定数组的大小。
其余部分:
使用输入表示的大小的唯一随机数填充数组。
发布于 2017-02-01 19:05:04
使用read-line
读取输入后,可以使用read-string
将其解析为整数,然后使用rand
生成随机数。之后,使用to-array
将它们转换为Java数组。下面的函数将提示用户输入数组大小,并将随机数数组从0返回到1:
(defn random-array-prompt []
(print "Enter array size:")
(let [n (read-string (read-line))]
(to-array (repeatedly n rand))))
之后,可以在repl中调用该函数:
(println (seq (bubble-sort (random-array-prompt))))
这将提示您输入大小并打印排序序列。
https://stackoverflow.com/questions/41981700
复制相似问题