英文:
how to sort 2D Array according to values in any given column in golang?
问题
我们有一个大小为N X M的二维数组和一个列号K(1<=K<=M)。任务是根据第K列的值对二维数组进行排序。
输入:如果我们的二维数组为(4X4的顺序)
39 27 11 42
10 93 91 90
54 78 56 89
24 64 20 65
按照第3列的值进行排序
输出:39 27 11 42
24 64 20 65
54 78 56 89
10 93 91 90
我认为在这个任务中需要使用Sort Slice: Len, Less, Swap in Interface,但我无法确定具体如何使用。
英文:
We are given a 2D array of order N X M and a column number K ( 1<=K<=m). Task is to sort the 2D array according to values in the Column K.
 Input : If our 2D array is given as (Order 4X4) 
        39 27 11 42 
        10 93 91 90 
        54 78 56 89 
        24 64 20 65
        Sorting it by values in column 3 
Output : 39 27 11 42 
         24 64 20 65 
         54 78 56 89 
         10 93 91 90 
I think in this task need to use Sort Slice: Len, Less, Swap in Interface but I can't figure out exactly how
答案1
得分: 1
你实际上可以使用sort.Slice,它可以按行对你的二维切片进行排序。
sort.Slice接受一个函数,用于比较每一行与其他行。在这个函数内部,你可以比较每一行中的列。
data := [][]int{
	{39, 27, 11, 42},
	{10, 93, 91, 90},
	{54, 78, 56, 89},
	{24, 64, 20, 65},
}
sortCol := 3
sort.Slice(data, func(i, j int) bool {
	return data[i][sortCol] < data[j][sortCol]
})
如果你有一个数组而不是切片,那么你可以使用与上面相同的sort.Slice,但是使用data[:]代替data。
https://go.dev/play/p/KcZepTz8SOZ
英文:
You can actually just use sort.Slice, which will sort the rows of your 2D slice row by row.
sort.Slice takes a function to compare each row against eachother. Inside this function you can compare the column in each row.
https://go.dev/play/p/cj1z7jBs2u5
data := [][]int{
	{39, 27, 11, 42},
	{10, 93, 91, 90},
	{54, 78, 56, 89},
	{24, 64, 20, 65},
}
sortCol := 3
sort.Slice(data, func(i, j int) bool {
	return data[i][sortCol] < data[j][sortCol]
})
If you have an array instead of a slice, then you can use the same sort.Slice as above, but use data[:] instead of data.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论