Search code examples
gobubble-sortpurely-functional

implementing bubble sort with go


Please help me implement bubble sort.It works fine if I call it with a hardcoded slice from the main() but if I call it with dynamic input from Scan it breaks

here is my code so far:

package main

import "fmt"

func main() {
    fmt.Println("Enter a maximum of 10 numbers: ")

    var inputs int
    fmt.Scanln(&inputs)
    inputSlice := make([]int, inputs)

    BubbleSort(inputSlice)

    fmt.Println(inputSlice)

}

func BubbleSort(input []int) {

    for i := 0; i < len(input)-1; i++ {
        for j := 0; j < len(input)-i-1; j++ {
            Swap(input, j)
        }
    }
}

func Swap(input []int, j int) {
    if input[j] > input[j+1] {
        input[j], input[j+1] = input[j+1], input[j]
    }
}

terminal:

coder:~/project$ go run bubblesort.go
Enter a maximum of 10 numbers:
12 24 54 65 11
coder:~/project$ 4 54 65 11
bash: 4: command not found

Solution

  • Do a little debugging by adding print lines in between your codes and see what's actually happening, you were just reading input the wrong way from command line

    After Taking Reference from this link as posted above in comments by Steffen Ullrich

    View In Go Playground

    package main
    
    import "fmt"
    
    func main() {
        fmt.Println(`Enter the number of integers`)
        var n int
        if m, err := Scan(&n); m != 1 {
            panic(err)
        }
        fmt.Println(`Enter the integers`)
        inputSlice := make([]int, n)
        ReadN(inputSlice, 0, n)
    
        //Your Input Printing Out
        fmt.Println(inputSlice)
    
        //Calling Function
        BubbleSort(inputSlice)
    
        //Output
        fmt.Println(inputSlice)
    
    }
    
    func BubbleSort(input []int) {
    
        for i := 0; i < len(input)-1; i++ {
            for j := 0; j < len(input)-i-1; j++ {
                Swap(input, j)
            }
        }
    }
    
    func Swap(input []int, j int) {
        if input[j] > input[j+1] {
            input[j], input[j+1] = input[j+1], input[j]
        }
    }
    
    //Additional Functions
    func ReadN(all []int, i, n int) {
        if n == 0 {
            return
        }
        if m, err := Scan(&all[i]); m != 1 {
            panic(err)
        }
        ReadN(all, i+1, n-1)
    }
    
    func Scan(a *int) (int, error) {
        return fmt.Scan(a)
    }