Sorting 相对于go中的另一个切片对切片进行排序
我正试图找出一种方法,将一个切片与另一个切片进行排序,例如: 我想对Sorting 相对于go中的另一个切片对切片进行排序,sorting,go,Sorting,Go,我正试图找出一种方法,将一个切片与另一个切片进行排序,例如: 我想对main\u切片与other\u切片 other_slice=[]int{3,5,1,2,7} main_slice=[]int{1,2,3,4,5} main_slice中的3对应于其他_slice中的最低值(1),4对应于第二低值(2);因此,我希望排序后的主\u片是:{3,4,1,2,5} 我使用教程作为参考,但无法提出解决方案,以下是我的尝试: package main import ( "fmt"
main\u切片
与other\u切片
other_slice=[]int{3,5,1,2,7}
main_slice=[]int{1,2,3,4,5}
main_slice
中的3
对应于其他_slice
中的最低值(1
),4
对应于第二低值(2
);因此,我希望排序后的主\u片是:{3,4,1,2,5}
我使用教程作为参考,但无法提出解决方案,以下是我的尝试:
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)
}
main\u slice
正在更改,但它没有实现我想要的功能,我做错了什么?在执行swap
时,您忘记交换其他\u 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]
}
就这样。非常感谢。
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]
}