Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

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)
}
share|improve this question

1 Answer 1

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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