I’m doing some revision for an upcoming repeat 🙁 and I’ve run into a problem with the following recursive implementation of Selection Sort in Scala.
For the most part this works, but it doesn’t seem to be swapping the first two values when they should be swapped. I’m sure it’s pretty basic but my problem solving cap is a little rusty at this stage
Any ideas greatly appreciated, here is the code I have so far:
object question3 {
def main(args : Array[String]) : Unit =
{
var arr = Array(8,9,8,5,2,4,1,6,3,7,5,-1,5,0,99)
arr = sort(arr, 0, 0, 0)
println("RESULT:")
arr.foreach(str=>print(str+","))
}
def sort(arr : Array[Int], n : Int, min : Int, j : Int): Array[Int] =
{
if(n == arr.length)
{
return arr
}
else
{
var j = n+1
var min = n
if(j < arr.length)
{
if(arr(j) < arr(min))
{
min = j
}
sort(arr, n+1, min, j+1)
}
if(min != n)
{
var t = arr(n)
arr(n) = arr(min)
arr(min) = t
}
sort(arr, n+1, min, j)
}
}
}
First, you never use the min and j parameters for anything, instead shadowing them with local definitions.
Second, you should not set the min variable until after the first recursive call. As your code stands, it sets min according to which of the first two initial elements is smaller, but never considers the possibility that there’s an even smaller one later in the array.
This gives something that looks more like an attempt at bubblesort than selection sort. If you want true selection sort you probably want a sepearate loop (or recursive function) to find the index of the minimal element first.