登录
首页 >  Golang >  Go问答

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

来源:stackoverflow

时间:2024-02-26 21:03:18 234浏览 收藏

各位小伙伴们,大家好呀!看看今天我又给各位带来了什么文章?本文标题《什么是正确终止条件下的冒泡排序交换?》,很明显是关于Golang的文章哈哈哈,其中内容主要会涉及到等等,如果能帮到你,觉得很不错的话,欢迎各位多多点评和分享!

问题内容

我正在学习 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]。我是否应该添加另一个条件,或者我在交换函数中使用指针的方式是否有问题?


正确答案


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
    }
}

您忘记比较 2 个变量,并且错误地使用了 i+1 而不是 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])
        }
    }
}

理论要掌握,实操不能落!以上关于《什么是正确终止条件下的冒泡排序交换?》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>