在go中相对于另一个切片对切片进行排序

时间:2015-01-01 18:32:26

标签: sorting go

我试图想出一种方法来对一个切片相对于另一个切片,例如:

我想针对main_slice

other_slice进行排序

other_slice = []int{3,5,1,2,7}

main_slice = []int{1,2,3,4,5}

3中的{p> main_slice对应other_slice1)中的最低值,4对应第二低(2);因此,我希望排序main_slice to be{3,4,1,2,5}

我使用this教程作为参考,但无法提出解决方案,这是我的尝试:

package main

import ( "fmt"
         "sort"
)

type TwoSlices struct {
    main_slice  []int
    other_slice  []int
}

type SortByOther TwoSlices

func (sbo SortByOther) Len() int {
    return len(sbo.main_slice)
}

func (sbo SortByOther) Swap(i, j int) {
    sbo.main_slice[i], sbo.main_slice[j] = sbo.main_slice[j], sbo.main_slice[i]
}

func (sbo SortByOther) Less(i, j int) bool {
    return sbo.other_slice[i] < sbo.other_slice[j] 
}


func main() {
    my_other_slice := []int{3,5,1,2,7}
    my_main_slice := []int{1,2,3,4,5} // sorted : {3,4,1,2,5}

    my_two_slices := TwoSlices{main_slice: my_main_slice, other_slice: my_other_slice}

    fmt.Println("Not sorted : ", my_two_slices.main_slice)

    sort.Sort(SortByOther(my_two_slices))
    fmt.Println("Sorted : ", my_two_slices.main_slice)

}

我的输出:

Not sorted :  [1 2 3 4 5]
Sorted :  [1 3 2 4 5]

main_slice正在改变,但它没有做我想做的,我做错了什么?

1 个答案:

答案 0 :(得分:2)

您忘记在other_slice的实施中交换Swap的元素:

func (sbo SortByOther) Swap(i, j int) {
    sbo.main_slice[i], sbo.main_slice[j] = sbo.main_slice[j], sbo.main_slice[i]
    sbo.other_slice[i], sbo.other_slice[j] = sbo.other_slice[j], sbo.other_slice[i]
}