Reputation: 67
I have to make a select sort function by passing it an array and using max element to sort it, with the two functions swap and max.
func Swap(x *int, y *int) {
aux := *x
*x = *y
*y = aux
}
func Max(array []int) int {
var pos int
if len(array) == 0 {
return -1
}
maxValue := array[0]
for i := 0; i < len(array); i++ {
if array[i] > maxValue {
maxValue = array[i]
pos = i
}
}
return pos
}
func Selection(array []int) {
for i := 0; i < len(array); i++ {
m := len(array) - 1
posMax := Max(array)
Swap(&array[posMax-i], &array[m-i])
}
}
It only orders the last element.
input: array := int{3,5,4,2,1} output: [3,1,4,2,5]
Why do I get this error and how can I fix it?
Upvotes: 1
Views: 111
Reputation: 67
func swap(x *int, y *int) {
*x, *y = *y, *x
}
func Selection(array []int) {
for i := 0; i < len(array); i++ {
m := len(array) - i
posMax := Max(array[:m])
Swap(&array[posMax],&array[m-1])
}
}
I fixed it
Upvotes: 2