Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I sort an array in Scala?

Tags:

sorting

scala

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 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.

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

like image 737
Dan Gravell Avatar asked Jul 15 '09 14:07

Dan Gravell


People also ask

How to Order Array in Scala?

Use the sortBy(attribute) Method to Sort an Array in Scala The sortBy method in Scala can sort based on one or more class attributes. This method can be used if we have an Ordering field type in the scope. Here, the default sorting is ascending as well.

What sorting algorithm does Scala use?

According to the Java 6 documentation, it therefore uses quicksort: The sorting algorithm is a tuned quicksort, adapted from Jon L.

What is the difference between SEQ and list in Scala?

A Seq is an Iterable that has a defined order of elements. Sequences provide a method apply() for indexing, ranging from 0 up to the length of the sequence. Seq has many subclasses including Queue, Range, List, Stack, and LinkedList. A List is a Seq that is implemented as an immutable linked list.


1 Answers

With Scala 2.8 or later it is possible to do:

List(3,7,5,2).sortWith(_ < _) 

that uses java.util.Arrays.sort, an implementation of quicksort.

like image 184
adelarsq Avatar answered Sep 27 '22 22:09

adelarsq