2 回答
TA貢獻(xiàn)1811條經(jīng)驗(yàn) 獲得超5個(gè)贊
package main
import (
"fmt"
"math/rand"
)
func main() {
testTwo := make([]int, 10)
for i := 0; i <= len(testTwo)-1; i++ {
fmt.Print("\n")
testTwo[i] = rand.Intn(10)
}
for i := 0; i <= len(testTwo)-1; i++ {
for j := i + 1; j <= len(testTwo)-1; j++ {
if testTwo[i] > testTwo[j] {
// here we swap pointers
testTwo[i], testTwo[j] = swap(testTwo[i], testTwo[j])
}
}
}
fmt.Print(testTwo)
}
/*
GO always sends arguments by value. Pointers cannot be swapped here, unless we use *int
*/
func swap(valOne, valTwo int) (int, int) {
if valOne <= valTwo {
return valOne, valTwo
} else {
return valTwo, valOne
}
}
TA貢獻(xiàn)1794條經(jīng)驗(yàn) 獲得超8個(gè)贊
您忘記比較 2 個(gè)變量并且錯(cuò)誤地使用i+1了 instead of j。
for i := 0; i <= len(testTwo)-1; i++ {
for j := i + 1; j <= len(testTwo)-1; j++ {
if testTwo[i] < testTwo[j] {
testTwo[i], testTwo[j] = swap(testTwo[i], testTwo[j])
}
}
}
- 2 回答
- 0 關(guān)注
- 127 瀏覽
添加回答
舉報(bào)
