4
\$\begingroup\$

I've made my first-ever program in Go, which sorts a given input of integers. There are 2 options: The list of unsorted integers and the algorithm to use.

Since it's my first go project I'm a bit unsure of a few things. For example, the "floating" variable declarations.

I think that the algorithms itself are okay, therefore I only post the executable program:

package main

import (
    "fmt"
    "flag"
    "strings"
    "strconv"
    "os"
    "github.com/afroewis/go-sorting-algorithms/sortalgos"
)

func main() {
    inputFlag := flag.String("input", "", "Input numbers to sort. Example: 10 20 5 1003 94 928")
    algoFlag := flag.String("algo", "", "Sorting algo to use. Available values: bubble, selection, insertion. ")
    flag.Parse()

    // Parse input
    input := strings.Split(*inputFlag, " ")
    var numbers [] int

    for i := 0; i < len(input); i++ {
        val, err := strconv.Atoi(input[i])

        if err != nil {
            panic(err)
        }

        numbers = append(numbers, val)
    }

    var result []int;

    switch *algoFlag {
    case "bubble":
        result = sortalgos.BubbleSort(numbers)
    case "selection":
        result = sortalgos.SelectionSort(numbers)
    case "insertion":
        result = sortalgos.InsertionSort(numbers)
    case "":
        fmt.Println("Error: -algo flag not set. For usage infos use ./main -help")
        os.Exit(1)
    }

    fmt.Println(result)
}
\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

I recommend looping through slice with range syntax.

for _, v := range(input) {
    val, err := strconv.Atoi(v)

    if err != nil {
        panic(err)
    }

    numbers = append(numbers, val)
}

You can replace case "" with default.

Besides that, it looks OK to me.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.