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] attribute. How to sort this array without manually encoding it?

I know that there is an object called Sorting , but it does not seem to work, since ArrayBuffer does not implement / extend class rights.

How to sort arrays of types ArrayBuffer[A] ?

+4
source share
2 answers

If you are using Scala 2.8, you can use the sortWith method of the ArrayBuffer[T] class, which inherits from the SeqLike attribute.

The following code snippets 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 correct order.

If you are using Scala 2.7, you can use the stableSort method of the stableSort object. This takes ArrayBuffer elements and creates an array of elements sorted in the correct order (specified by closure as an argument, ascending by default).

For instance:

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

The important question is what you want to do with ArrayBuffer . Typically, Buffer used within different algorithms to improve the performance of intermediate results. If you use it for this, take a look at ways to sort the collection that you want to return at the end of your algorithm. The Sorting object already provides a way to convert an ArrayBuffer to a sorted Array .

From a Buffer class skalyadok:

Buffers are used to gradually create sequences of elements.

Since you are using it with Actor s, you can use it for some lineup of actors - in this case, you can see the Queue collection.

Hope this helps,

- Flavy Chipchigan

+7
source

Btw, the Actor class is my own class used for "Actors" in a world created using my new game engine for scala ("Awesome Game Engine for scala ~ AGES"), so it has nothing to do with the actor class concurrency. In addition, scala's list implementations are jungle, everything is either deprecated or implemented differently .... ArrayBuffer works for my needs (my need for an array of variable sizes to accommodate participants).

Hope this clarifies :)

0
source

All Articles