0

What do I have: algorithm in pseudocode from the "Computer Science Distilled" book (p. 27)

function selection_sort(list)
    for current <- 1 ... list.length - 1
        smallest <- current
        for i <- current + 1 ... list.length
            if list[i] < list[smallest]
                smallest <- i
        list.swap_items(current, smallest)

I'm trying to understand it, so I wrote it in Go:

func main() {
    list := []int{5, 2, 7, 9}
    for current := 1; current < len(list)-1; current++ {
        smallest := current
        for i := current + 1; i < len(list); i++ {
            if list[i] < list[smallest] {
                smallest = i
            }
        }
        current_tmp := list[current]
        smallest_tmp := list[smallest]
        list[current], list[smallest] = smallest_tmp, current_tmp
    }
    fmt.Printf("%v\n", list)
}

Playground

And output is [5 2 7 9]. Am I missing something?

1 Answer 1

1

I don't know Go, but googling confirms that Go has zero based numbering. In your example you start from 1 (should be 0).

Another thing -- why do you need current_tmp and smallest_tmp?

So I suggest the following:

func main() {
    list := []int{5, 2, 7, 9}
    for current := 0; current < len(list)-1; current++ {
        smallest := current
        for i := current + 1; i < len(list); i++ {
            if list[i] < list[smallest] {
                smallest = i
            }
        }
        list[current], list[smallest] = list[smallest], list[current]
    }
    fmt.Printf("%v\n", list)
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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.