如何在Scala中对数组排序? [英] How do I sort an array in Scala?

查看:271
本文介绍了如何在Scala中对数组排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以看到有一个排序对象Sorting,它具有快速排序方法,quickSort,就在它上面.

I can see there's a sorting object, Sorting, with a quicksort method, quickSort, on it.

使用它对任意类型的对象数组进行排序的代码示例是什么?看来我需要传递Orderable特征的实现,但是我不确定语法.

What would be a code example of using it, sorting an array of object of arbitrary type? It looks like I need to pass in an implementation of the Orderable trait, but I am unsure of the syntax.

此外,我更希望以"Scala方式"进行回答.我知道我只能使用Java库.

Also, I would prefer answers doing this the 'Scala way'. I know I can just use a Java library.

推荐答案

Sorting.quickSort声明用于获取数字或字符串数​​组的函数,但我假设您的意思是要对自己类的对象列表进行排序?

Sorting.quickSort declares functions for taking an Array of numbers or Strings, but I'm assuming you mean you want to sort a list of objects of your own classes?

我认为您正在查看的功能是

The function I think you're looking at is

quickSort [K](a : Array[K])(implicit view$1 : (K) => Ordered[K]) : Unit

如果我没看错,这意味着Array中的对象必须具有Ordered特性.因此,您的类必须扩展Ordered(或必须将其混入),因此必须实现该特征的compare方法.

Which, if I'm reading this right, means that the objects in the Array must have the Ordered trait. So your class must extend Ordered (or must mix it in), and therefore must implement the compare method of that trait.

因此,从本书中摘录一个例子:

So to rip off an example from the book:

class MyClass(n: Int) extends Ordered[MyClass] {
   ...
  def compare(that: MyClass) =
    this.n - that.n
}

因此,给定一个Array [MyClass],则Sorting.quickSort应该可以工作.

So given an Array[MyClass], then Sorting.quickSort should work.

这篇关于如何在Scala中对数组排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆