1

In Java I can write

private final List<Point> points = ...;
...
Collections.sort(points.subList(start, end), sorter);

(This is used as part of an algorithm that sorts the entire List in a particular way.)

I'd like to be able to express the equivalent in Scala with Array. I have tried this:

val a = Array("z", "y", "x", "w", "v")
val b = a.slice(1, 4)
Sorting.quickSort(b)

But unfortunately it doesn't work as the slice copies a. How can I sort part of an array in Scala?

Edit: the intention is that sorter becomes a Scala Ordering.

1 Answer 1

4

As an Array[T] in Scala is with one to one correspondents to a Java array, you can use the same in place java.util.Arrays.sort:

scala> val arr = Array(1, 5, 2, 3, 7, 9)
arr: Array[Int] = Array(1, 5, 2, 3, 7, 9)

scala> java.util.Arrays.sort(arr, 0, 3)

scala> arr
res22: Array[Int] = Array(1, 2, 5, 3, 7, 9)
Sign up to request clarification or add additional context in comments.

5 Comments

I should have said: I wanted to use a Scala Ordering with it... (see sorter above). Does that work?
So you want to use Ordering on a collection, but modify it partially and in place?
Yes please, if possible. If not I will just fall back to using Java Comparator with a Java ArrayList.
@Mohan do you have any particular reasons for wanting to use Ordering for this ?
A general (and perhaps in this case misguided?) desire not to mix Java and Scala constructs willy-nilly.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.