如何在 Scala 中对数组进行排序?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1131925/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I sort an array in Scala?
提问by Dan Gravell
I can see there's a sorting object, Sorting, with a quicksortmethod, quickSort, on it.
我可以看到有一个排序对象,Sorting,上面有一个快速排序方法,quickSort。
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 Orderabletrait, but I am unsure of the syntax.
使用它的代码示例是什么,对任意类型的对象数组进行排序?看起来我需要传入Orderable特征的实现,但我不确定语法。
Also, I would prefer answers doing this the 'Scala way'. I know I can just use a Java library.
另外,我更喜欢以“Scala 方式”来做这件事的答案。我知道我只能使用 Java 库。
采纳答案by skaffman
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?
Sorting.quickSort 声明了用于获取数字或字符串数组的函数,但我假设您的意思是要对您自己的类的对象列表进行排序?
The function I think you're looking at is
我认为您正在查看的功能是
quickSort [K](a : Array[K])(implicit view : (K) => Ordered[K]) : Unit
Which, if I'm reading this right, means that the objects in the Array must have the Orderedtrait. So your class must extend Ordered(or must mix it in), and therefore must implement the comparemethod of that trait.
如果我没看错,这意味着 Array 中的对象必须具有Orderedtrait。所以你的类必须扩展Ordered(或必须混合),因此必须实现该compare特性的方法。
So to rip off an example from the book:
因此,从书中窃取一个示例:
class MyClass(n: Int) extends Ordered[MyClass] {
...
def compare(that: MyClass) =
this.n - that.n
}
So given an Array[MyClass], then Sorting.quickSort should work.
所以给定一个 Array[MyClass],那么 Sorting.quickSort 应该可以工作。
回答by adelarsq
With Scala 2.8 or later it is possible to do:
使用 Scala 2.8 或更高版本,可以执行以下操作:
List(3,7,5,2).sortWith(_ < _)
that uses java.util.Arrays.sort, an implementation of quicksort.
使用java.util.Arrays.sort,一种快速排序的实现。
回答by hendrik
Nowadays this one works too:
现在这个也有效:
List(3,7,5,2).sorted
List(3,7,5,2).sorted
回答by Peter Recore
If you just want to sort things, but aren't married to the Sorting object in particular, you can use the sort method of List. It takes a comparison function as an argument, so you can use it on whatever types you'd like:
如果您只是想对事物进行排序,但又不想特别与 Sorting 对象结合,则可以使用 List 的 sort 方法。它需要一个比较函数作为参数,所以你可以在任何你喜欢的类型上使用它:
List("Steve", "Tom", "John", "Bob").sort((e1, e2) => (e1 compareTo e2) < 0)
List(1, 4, 3, 2).sort((e1, e2) => (e1 < e2))
Lists probably qualify as "more scalaish" than arrays.
列表可能比数组更“scalaish”。
From the scala api docs:
来自 scala api文档:
def sort(lt : (A, A) => Boolean) : List[A]
Sort the list according to the comparison function <(e1: a, e2: a) =>Boolean, which should be true iff e1 is smaller than e2.
def sort(lt : (A, A) => Boolean) : List[A]
Sort the list according to the comparison function <(e1: a, e2: a) =>布尔值,当 e1 小于 e2 时应该为真。
回答by Daniel C. Sobral
val array = Array((for(i <- 0 to 10) yield scala.util.Random.nextInt): _*)
scala.util.Sorting.quickSort(array)
Scala's "default" array is a mutable data structure, very close to Java's Array. Generally speaking, that means an "array" is not very Scala-ish, even as mutable data structures go. It serves a purpose, though. If array is the right data type for your need, then that is how you sort it. There are other sorting methods on object Sorting, by the way.
Scala 的“默认”数组是一个可变数据结构,非常接近 Java 的 Array。一般来说,这意味着“数组”不是非常 Scala 风格,即使是可变数据结构。不过,它是有目的的。如果数组是您需要的正确数据类型,那么这就是您对其进行排序的方式。顺便说一下,对象排序还有其他排序方法。
I think I just realized what your question is... you don't need to pass any implicit parameter (it's implicit, after all). That parameter exists to say that there must be some way to convert the type K into an Ordered[K]. These definitions already exist for Scala's classes, so you don't need them.
我想我刚刚意识到你的问题是什么......你不需要传递任何隐式参数(毕竟它是隐式的)。该参数的存在说明必须有某种方法将类型 K 转换为 Ordered[K]。Scala 的类已经存在这些定义,因此您不需要它们。
For an arbitrary class you can define it this way:
对于任意类,您可以通过以下方式定义它:
scala> case class Person(name: String)
defined class Person
scala> val array = Array(Person("John"), Person("Mike"), Person("Abe"))
array: Array[Person] = Array(Person(John), Person(Mike), Person(Abe))
scala> scala.util.Sorting.quickSort(array)
<console>:11: error: no implicit argument matching parameter type (Person) => Ordered[Person] was found.
scala.util.Sorting.quickSort(array)
^
scala> class OrderedPerson(val person: Person) extends Ordered[Person] {
| def compare(that: Person) = person.name.compare(that.name)
| }
defined class OrderedPerson
scala> implicit def personToOrdered(p: Person) = new OrderedPerson(p)
personToOrdered: (p: Person)OrderedPerson
scala> scala.util.Sorting.quickSort(array)
scala> array
res8: Array[Person] = Array(Person(Abe), Person(John), Person(Mike))
Now, if Person was Ordered to begin with, this wouldn't be a problem:
现在,如果 Person 被命令开始,这不会是一个问题:
scala> case class Person(name: String) extends Ordered[Person] {
| def compare(that: Person) = name.compare(that.name)
| }
defined class Person
scala> val array = Array(Person("John"), Person("Mike"), Person("Abe"))
array: Array[Person] = Array(Person(John), Person(Mike), Person(Abe))
scala> scala.util.Sorting.quickSort(array)
scala> array
res10: Array[Person] = Array(Person(Abe), Person(John), Person(Mike))
回答by Kim Stebel
While the accepted answer isn't wrong, the quicksort method provides more flexibility than that. I wrote this example for you.
虽然公认的答案没有错,但快速排序方法提供了更多的灵活性。我为你写了这个例子。
import System.out.println
import scala.util.Sorting.quickSort
class Foo(x:Int) {
def get = x
}
//a wrapper around Foo that implements Ordered[Foo]
class OrdFoo(x:Foo) extends Ordered[Foo] {
def compare(that:Foo) = x.get-that.get
}
//another wrapper around Foo that implements Ordered[Foo] in a different way
class OrdFoo2(x:Foo) extends Ordered[Foo] {
def compare(that:Foo) = that.get-x.get
}
//an implicit conversion from Foo to OrdFoo
implicit def convert(a:Foo) = new OrdFoo(a)
//an array of Foos
val arr = Array(new Foo(2),new Foo(3),new Foo(1))
//sorting using OrdFoo
scala.util.Sorting.quickSort(arr)
arr foreach (a=>println(a.get))
/*
This will print:
1
2
3
*/
//sorting using OrdFoo2
scala.util.Sorting.quickSort(arr)(new OrdFoo2(_))
arr foreach (a=>println(a.get))
/*
This will print:
3
2
1
*/
This shows how implicit and explicit conversions from Foo to some class extending Ordered[Foo] can be used to get different sort orders.
这显示了如何使用从 Foo 到某个扩展 Ordered[Foo] 的类的隐式和显式转换来获得不同的排序顺序。
回答by Ahmad Al-Kurdi
I prefer to user Sorting util
我更喜欢用户排序工具
Example :
例子 :
val arr = Array(7,5,1, 9,2)
scala.util.Sorting.quickSort(arr)
please read this for more info Sorting util
请阅读本文以获取更多信息Sorting util

