ativg
ativg

Reputation: 7

Sorting 2D String array in Scala

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

Upvotes: 0

Views: 325

Answers (1)

marios
marios

Reputation: 8996

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.

Upvotes: 2

Related Questions