冒泡排序中交换的正确终止条件是什么?

我正在学习 golang,我正在尝试通过编写冒泡排序和使用指针来工作。


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++ {


            testTwo[i], testTwo[i+1] = swap(testTwo[i], testTwo[i+1])

        }

    }

}



/*

Swaps the pointers of two adjacent elements in an array

*/

func swap(valOne, valTwo int) (int, int) {


    valAddress := &valOne

    valAddressTwo := &valTwo


    if valOne <= valTwo {

        temp_address := *valAddressTwo

        *valAddressTwo = valOne

        *valAddress = temp_address


    } else {

        temp_address := *valAddress

        *valAddress = valTwo

        *valAddressTwo = temp_address

    }


    return valOne, valTwo

}


这是迄今为止正在做的事情的一个例子。输入切片可能是 [4 1 2 9 8 4 1 5 7 6]。但它没有对所有内容进行排序。[1 4 9 2 4 8 5 1 6 7]。我应该添加另一个条件还是我在交换函数中使用指针的方式有问题?


FFIVE
浏览 81回答 2
2回答

四季花海

package mainimport (&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "math/rand")func main() {&nbsp; &nbsp; testTwo := make([]int, 10)&nbsp; &nbsp; for i := 0; i <= len(testTwo)-1; i++ {&nbsp; &nbsp; &nbsp; &nbsp; fmt.Print("\n")&nbsp; &nbsp; &nbsp; &nbsp; testTwo[i] = rand.Intn(10)&nbsp; &nbsp; }&nbsp; &nbsp; for i := 0; i <= len(testTwo)-1; i++ {&nbsp; &nbsp; &nbsp; &nbsp; for j := i + 1; j <= len(testTwo)-1; j++ {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if testTwo[i] > testTwo[j] {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // here we swap pointers&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; testTwo[i], testTwo[j] = swap(testTwo[i], testTwo[j])&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; 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) {&nbsp; &nbsp; if valOne <= valTwo {&nbsp; &nbsp; &nbsp; &nbsp; return valOne, valTwo&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; return valTwo, valOne&nbsp; &nbsp; }}

慕田峪9158850

您忘记比较 2 个变量并且错误地使用i+1了 instead of j。for i := 0; i <= len(testTwo)-1; i++ {&nbsp; &nbsp; for j := i + 1; j <= len(testTwo)-1; j++ {&nbsp; &nbsp; &nbsp; &nbsp; if testTwo[i] < testTwo[j] {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; testTwo[i], testTwo[j] = swap(testTwo[i], testTwo[j])&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go