How do I sort an array in Scala?

后端 未结 7 679
北恋
北恋 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:35

    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:

    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.

    From the scala api docs:

    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.

提交回复
热议问题