简体   繁体   English

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

[英]Sort slice with respect to another slice in go

I am trying to figure out a way to sort one slice with respect to the other, for example: 我试图找出一种方法来相对于另一个切片排序,例如:

I want to sort main_slice with respect to other_slice 我要排序main_slice相对于other_slice

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

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

3 in main_slice corresponds to lowest value in other_slice ( 1 ), 4 to the second lowest ( 2 ); main_slice 3对应于other_slice1 )中的最低值, 4对应于第二低( 2 ); therefore, I expect sorted main_slice to be : {3,4,1,2,5} 因此,我希望将main_slice to be排序main_slice to be{3,4,1,2,5}

I used this tutorial as reference, but could not come up with a solution, here is my try: 我使用教程作为参考,但无法提出解决方案,这是我的尝试:

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)

}

My output: 我的输出:

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

main_slice is getting changed, but it does not do what I want, what am I doing wrong? main_slice正在改变,但它没有做我想要的,我做错了什么?

You forgot to swap the elements of other_slice in the implementation of Swap : 你忘了在Swap的实现中Swap other_slice的元素:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM