第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問(wèn)題,去搜搜看,總會(huì)有你想問(wèn)的

冒泡排序中交換的正確終止條件是什么?

冒泡排序中交換的正確終止條件是什么?

Go
FFIVE 2022-12-19 11:57:12
我正在學(xué)習(xí) golang,我正在嘗試通過(guò)編寫(xiě)冒泡排序和使用指針來(lái)工作。package mainimport (    "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}這是迄今為止正在做的事情的一個(gè)例子。輸入切片可能是 [4 1 2 9 8 4 1 5 7 6]。但它沒(méi)有對(duì)所有內(nèi)容進(jìn)行排序。[1 4 9 2 4 8 5 1 6 7]。我應(yīng)該添加另一個(gè)條件還是我在交換函數(shù)中使用指針的方式有問(wèn)題?
查看完整描述

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

    }

}


查看完整回答
反對(duì) 回復(fù) 2022-12-19
?
慕田峪9158850

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])

        }

    }

}


查看完整回答
反對(duì) 回復(fù) 2022-12-19
  • 2 回答
  • 0 關(guān)注
  • 127 瀏覽
慕課專(zhuān)欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢(xún)優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)