duanqia9034 2015-01-01 18:32
浏览 43
已采纳

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

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

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); therefore, I expect sorted 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?

  • 写回答

1条回答 默认 最新

  • duanmianzhou5353 2015-01-01 18:47
    关注

    You forgot to swap the elements of other_slice in the implementation of 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]
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 mmocr的训练错误,结果全为0
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀