douzi8916 2017-03-09 23:08
浏览 195
已采纳

如何在golang中按索引排序

I'm having difficulty porting some code from matlab to golang I want to know how can I get array indices after sorting them in golang, and then how can I use these indices to re-arrange another array? for example the matlab code below does that but I can't figure out doing the same thing in Go. Any help is deeply appreciated.

x=[3 4 2 1 6];
y=[11 12 15 16 17];
[sorted_x_vals, sorted_x_indices]=sort(x);
c=y(sorted_x_indices);  // re-arrange y according to the sorted indices

// c= 16 15 11 12 17

Thanks a lot in advance

  • 写回答

1条回答 默认 最新

  • dpwdsmbvm496180204 2017-03-09 23:35
    关注

    You can crate a sort.Interface implementation to sort the slices in unison, based on the first slice's values:

    https://play.golang.org/p/y0EFj8wUN0

    type by struct {
        Indices []int
        Values  []int
    }
    
    func (b by) Len() int           { return len(b.Values) }
    func (b by) Less(i, j int) bool { return b.Indices[i] < b.Indices[j] }
    func (b by) Swap(i, j int) {
        b.Indices[i], b.Indices[j] = b.Indices[j], b.Indices[i]
        b.Values[i], b.Values[j] = b.Values[j], b.Values[i]
    }
    
    func main() {
        x := []int{3, 4, 2, 1, 6}
        y := []int{11, 12, 15, 16, 17}
    
        sort.Sort(by{Indices: x, Values: y})
        fmt.Println(x)
        fmt.Println(y)
    }
    
    // [1 2 3 4 6]
    // [16 15 11 12 17]
    

    Or if you wanted to sort any number of slices like this you could define a [][]int type like so

    type matrix [][]int
    func (m matrix) Len() int {return len(m[0])}
    func (m matrix) Less(i, j int) bool { return m[0][i] < m[0][j] }
    func (m matrix) Swap(i, j int) {
        for _, s := range m {
            s[i], s[j] = s[j], s[i]
        }
    }
    
    func main() {
        x := []int{3, 4, 2, 1, 6}
        y := []int{11, 12, 15, 16, 17}
        z := []int{22, 33, 44, 55, 66}
    
        sort.Sort(matrix{x, y, z})
        fmt.Println(x)
        fmt.Println(y)
        fmt.Println(z)
    }
    // [1 2 3 4 6]
    // [16 15 11 12 17]
    // [55 44 22 33 66]
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?