0

Hi I'm trying to sort a matrix by a column in alphabetical order

I tried with this: It's just a bubblesort that I tried out var artists2=Array.ofDimString// Artist Name,Year

var compare=0
var aux2=""
for(i <- 0 to 99){
        for(j <- 0 to 993){
          compare = artists(j)(0).compareTo(artists(j+1)(0))
      if (compare < 0)  { //a is smaller  b>a
        aux2=artists(j)(0)
                artists(j)(0)=artists(j+1)(0)
                artists(j+1)(0)=aux2

                aux2=artists(j)(1)
                artists(j)(1)=artists(j+1)(1)
                artists(j+1)(1)=aux2
      }  
        }
}
println(artists.map(_.mkString(" ")).mkString("\n"))

But I get a null pointer Exception I know this is not suposed to work with string so if you have any suggestions please let me know my matrix has tu colums artists and years I want to sort it out by the artists column but still conserve each artist year

1 Answer 1

2

If you want to sort an array you can simply call the sortBy method in Scala.

scala> val artists = Array(("ArtistA",1987), ("ArtistC", 1545), ("ArtistB", 2014))
artists: Array[(String, Int)] = Array((ArtistA,1987), (ArtistC,1545), (ArtistB,2014))

scala> artists.sortBy(_._1)
Array[(String, Int)] = Array((ArtistA,1987), (ArtistB,2014), (ArtistC,1545))

Here is the case where your data are not in an Array[(String, Int)] type but in a 2D Array. Note that unlike tuples, 2D Arrays cannot support having multiple types (you can but they lose their type to 'Any'). So the Array will be of type Array[Array[String]].

val d2 = Array(Array("ArtistA","ArtistC","ArtistB"), Array("1987", "1545", "2014"))
d2: Array[Array[String]] = Array(Array(ArtistA, ArtistC, ArtistB), Array(1987, 1545, 2014))

val sorted = d2(0).zip(d2(1)).sortBy(_._1).unzip  
sorted: (Array[String], Array[String]) = (Array(ArtistA, ArtistB, ArtistC),Array(1987, 2014, 1545))

The idea here is that you first break the 2D array using zip to create an array of tuples. Next you sort it, and finally you unzip it.

Sign up to request clarification or add additional context in comments.

3 Comments

I get this error not enough arguments for method sortBy: (implicit ord: scala.math.Ordering[B])Array[Array[String]]. Unspecified value parameter ord.
Can you give me an example input data? Similar to what I do here with 'artists'?
"Korn","1987" I want to sort it out by artists alphabeticallly, the two fields are strings

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.