How do I sort an array in Scala?

后端 未结 7 639
北恋
北恋 2020-12-07 12:54

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

What would be a code example of using it, sorting

7条回答
  •  时光说笑
    2020-12-07 13:56

    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.

提交回复
热议问题