Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort ArrayBuffer[A] in scala?

I have an array in Scala with the class ArrayBuffer[Actor], where Actor is a class that implements the Ordered[Actor] trait. How do I sort this array without coding it manually?

I know there is an object called Sorting, but it doesnt seem to work since ArrayBuffer doesn't implement/extend the right classes.

How do I sort ArrayBuffer[A] type arrays?

like image 591
Felix Avatar asked Feb 28 '23 21:02

Felix


1 Answers

If you are using Scala 2.8, you could use the sortWith method of the ArrayBuffer[T] class, which is inherited from the SeqLike trait.

The following code snippet sorts an ArrayBuffer[T] object in ascending order:

def ascendingSort[T <% Ordered[T]](xs: ArrayBuffer[T]) = xs.sortWith(_ < _)

Note that this does not mutate the actual ArrayBuffer, but creates a new one with the elements in the right order.

If you are using Scala 2.7, you could use the stableSort method of the Sorting object. This takes the elements of the ArrayBuffer and produces an array of elements sorted in the right order (given by a closure as an argument, ascending as a default).

For example:

val a = new scala.collection.mutable.ArrayBuffer[Int]()
a += 5
a += 2
a += 3

scala.util.Sorting.stableSort(a)

The important question is what do you want to do with the ArrayBuffer. Usually, a Buffer is used internally in different algorithms in order to increase the performance of intermediate results. If you are using it for that, have a look at the ways of sorting the collection you want to return at the end of your algorithm. The Sorting object already provides a way of transforming an ArrayBuffer into a sorted Array.

From the scaladoc of the Buffer class:

Buffers are used to create sequences of elements incrementally

As you are using it with Actors, it might be used for some kind of actor queue - in which case, you might want to have a look at the Queue collection.

Hope it helps,

-- Flaviu Cipcigan

like image 130
Flaviu Cipcigan Avatar answered Mar 06 '23 21:03

Flaviu Cipcigan