我試圖找出一種方法來對一個切片進(jìn)行排序,例如:我要排序main_slice相對于other_sliceother_slice = []int{3,5,1,2,7}main_slice = []int{1,2,3,4,5}3inmain_slice對應(yīng)于other_slice( 1) 中的最低值,4第二低 ( 2);因此,我希望排序main_slice to be:{3,4,1,2,5}我使用本教程作為參考,但無法提出解決方案,這是我的嘗試:package mainimport ( "fmt" "sort")type TwoSlices struct { main_slice []int other_slice []int}type SortByOther TwoSlicesfunc (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 回答

慕碼人2483693
TA貢獻(xiàn)1860條經(jīng)驗 獲得超9個贊
您忘記交換other_slice的實現(xiàn)中的元素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]
}
- 1 回答
- 0 關(guān)注
- 168 瀏覽
添加回答
舉報
0/150
提交
取消