Here's my code for performing a selection sort using 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()
However, the output I see is still an unsorted array:
Before sort : [1, 5, 2, 3, 7, 4, 6, 8, 9]
After sort : [1, 5, 2, 3, 7, 4, 6, 8, 9]
I am very new to Groovy. I'm supposed to insert the logic within a closure only. I'm not sure what I need to change in the closure I have created in my code above. Please help.
You are using the wrong index when calculating the position of the minimum value; you should use j instead of i (added println to show iterations):
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"
}
So that selectionSort([1,5,2,4,3,8,7,9]) yields:
[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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With