What is the correct terminating condition for swapping in bubble sort?

Issue

I am learning golang, and I am trying to work through writing bubblesort and working with pointers.

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
}

This is an example of what is being done so far. The input slice might be
[4 1 2 9 8 4 1 5 7 6]. But it stops short of sorting everything.[1 4 9 2 4 8 5 1 6 7]. Is there another condition I should add or is there something wrong with how I am using the pointers in the swap function?

Solution

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

Answered By – Dmitry Harnitski

Answer Checked By – Willingham (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.