Понимание алгоритма сортировки из книги "Информатика" - PullRequest
0 голосов
/ 03 апреля 2020

Что у меня есть: алгоритм в псевдокоде из книги "Computer Science Distilled" (стр. 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)

Я пытаюсь понять это, поэтому я написал это в 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)
}

Детская площадка

И вывод [5 2 7 9]. Я что-то упустил?

1 Ответ

1 голос
/ 03 апреля 2020

Я не знаю Go, но поиск в Google подтверждает, что Go имеет нумерацию с нуля. В вашем примере вы начинаете с 1 (должно быть 0).

Другое дело - зачем вам нужны current_tmp и smallest_tmp?

Поэтому я предлагаю следующее :

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)
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...