0

I'm trying to implement Bubble Sort in Scala.

This is my implementation:

object Example {

  def bubbleSort(arr:Array[Int])={
    var temp=0
    for(i<- 1 until arr.length-1 ; j<- 1 until (arr.length-1-i)){
      if(arr(j-1)>arr(j)) {
        temp=arr(j-1)
        arr(j-1)=arr(j)
        arr(j)=temp 
       }
     }
     arr
  }

  def main(args: Array[String]): Unit = {
    var x = bubbleSort(Array(3, 60, 35, 2, 45, 320, 5))
    println(x)
  }

}

The problem is that the following output is printed:

[I@68be2bc2

What's the problem?

stefanobaghino
  • 11,253
  • 4
  • 35
  • 63

1 Answers1

1

The problem with your code is here:

def main(args: Array[String]): Unit = {
    var x = bubbleSort(Array(3, 60, 35, 2, 45, 320, 5))
    println(x)
  }

you are really printing the reference of the array x not the elements of it.

to print each element of the array use

def main(args: Array[String]): Unit = {
    var x = bubbleSort(Array(3, 60, 35, 2, 45, 320, 5))
    x.foreach(println)
  }
Ben
  • 1,414
  • 2
  • 13
  • 18
Aditya Agarwal
  • 693
  • 1
  • 10
  • 17