如何根据Golang的任何给定列中的任何给定列中的值对2D数组进行排序?
我们给出了订单NXM和列编号K(1< = K< = m)的2D数组。任务是根据K列中的值对2D数组进行排序。
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
我认为在此任务中需要使用Sort Slice:Len,Simelt,在接口中交换,但我无法确切地弄清楚如何确切地弄清楚如何
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
实际上,您可以只使用
sort.slice
,它将按行分类2D切片的行。sort.slice
采用一个函数,将每一行与彼此进行比较。在此功能中,您可以比较每行中的列。https://go.dev/play/pplay/p/cj1z7jbs2u5
如果您有阵列而不是阵列切片,然后您可以使用相同的
sort.slice
如上所述,但是使用data [:]
而不是data
。https://go.dev/play/pplay/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
If you have an array instead of a slice, then you can use the same
sort.Slice
as above, but usedata[:]
instead ofdata
.https://go.dev/play/p/KcZepTz8SOZ