【发布时间】:2017-02-01 14:03:25
【问题描述】:
目前正在编程冒泡排序算法。 我找到了网上某人的源代码:
Scanner sc = new Scanner(System.in);
System.out.println("Enter the size of the array which you would like to create: ");
应用程序现在做什么,它接受用户的输入数字。并制作一个随机数数组。使用这个数组,它应用了冒泡排序算法。
现在,我正在尝试将其翻译为 Clojure。 我知道用户输入可以通过函数来实现:
Flush
和
read-line
除此之外,我不明白如何获取所需数组大小的用户输入,然后创建一个随机数数组,然后应用冒泡排序。 到目前为止,这就是我所拥有的(从 Rosetta 网站找到的 Bubblesort。):
(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)
输入应确定数组的大小。
剩余部分:
用输入表示的大小的唯一随机数填充数组。
【问题讨论】:
标签: java algorithm intellij-idea clojure bubble-sort