这是我使用Groovy执行选择排序的代码:
class SelectionSorting {
void sorting() {
def sortmethod = {
List data = [ 1, 5, 2, 3, 7, 4, 6, 8, 9, ]
def n = data.size()
println "Before sort : " + data
for(def i in 0..n) {
def position=i
for(def j in i+1..n) {
if(data[position] > data[i])
position=i
}
if(position!=i) {
swap(data[i],data[position])
}
}
println "After sort : " + data
}
sortmethod()
}
}
SelectionSorting s = new SelectionSorting()
s.sorting()
但是,我看到的输出仍然是一个未排序的数组:
Before sort : [1, 5, 2, 3, 7, 4, 6, 8, 9]
After sort : [1, 5, 2, 3, 7, 4, 6, 8, 9]
我是Groovy的新手。我应该只在闭包中插入逻辑。我不确定我在上面的代码中创建的闭包中需要更改什么。请帮忙。
答案 0 :(得分:2)
在计算最小值的位置时,您使用了错误的索引;您应该使用j
代替i
(添加println
来显示迭代次数):
def selectionSort = { data ->
int n = data.size()
for (int i = 0; i < n - 1; i++) {
// Find the index (position) of the minimum value
position = i
for(int j = i + 1; j < n; j++) {
if(data[j] < data[position]) {
position = j
}
}
// Swap
if (position != i) {
temp = data[position]
data[position] = data[i]
data[i] = temp
}
println data
}
println "result: $data"
}
这样selectionSort([1,5,2,4,3,8,7,9])
就会产生:
[1, 5, 2, 4, 3, 8, 7, 9]
[1, 2, 5, 4, 3, 8, 7, 9]
[1, 2, 3, 4, 5, 8, 7, 9]
[1, 2, 3, 4, 5, 8, 7, 9]
[1, 2, 3, 4, 5, 8, 7, 9]
[1, 2, 3, 4, 5, 7, 8, 9]
[1, 2, 3, 4, 5, 7, 8, 9]
result: [1, 2, 3, 4, 5, 7, 8, 9]