HiveBrain v1.2.0
Get Started
← Back to all entries
patterngoMinor

Command line flags & sorting algorithms

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
sortinglinealgorithmsflagscommand

Problem

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

Solution

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.

Code Snippets

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

    if err != nil {
        panic(err)
    }

    numbers = append(numbers, val)
}

Context

StackExchange Code Review Q#67920, answer score: 2

Revisions (0)

No revisions yet.