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)
}
Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Oct 25, 2014 at 14:44
\$\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.

answered Nov 12, 2014 at 15:01
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.