Home > front end >  What is the correct terminating condition for swapping in bubble sort?
What is the correct terminating condition for swapping in bubble sort?

Time:05-31

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?

CodePudding user response:

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

CodePudding user response:

You forgot to compare 2 variables and you have mistaken using 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])
        }
    }
}
  • Related