I have been attempting to learn Scala lately and so have produced a couple of different sorting algorithms to build up my basics.
I think I have been lucky with the methods returning exactly what I have wanted, but for MergeSort I have implemented recursive methods that could return one of two different values and could logically be placed into two different values of the same type (as I believe Scala does)
In order to get my program to sort properly I have put a temp variable in order to grab the returning value and then be able to use it.
Is there a better way to return the values that will not need me to create these temporary values or should I have been doing something else?
Example:
def merge(left: ArrayBuffer[Int], right: ArrayBuffer[Int]): ArrayBuffer[Int]
returns an ArrayBuffer, how does the scala language figure out which value to put the returned value into or does it need a variable on the returning end to capture the value that is being returned?
merge(left, right)
This does nothing while,
var tempResult = merge(left, right)
Solves the problem.
Am I doing something wrong in the first instance (due to my experience with single parameter methods returning to the proper variable), or is this the standard way to return the values, by returning to a variable?
MergeSortClass.scala
import scala.collection.mutable.ArrayBuffer
class MergeSortClass {
def mergeSort(array: ArrayBuffer[Int]): ArrayBuffer[Int] = {
if (array.size <= 1) {
array
} else {
var left = ArrayBuffer[Int]()
var right = ArrayBuffer[Int]()
var middle = array.size / 2
for (i <- 0 until middle) {
left += array(i)
}
for (i <- middle until array.size) {
right += array(i)
}
//-->>>TheseValues Below
var leftTemp = mergeSort(left);
var rightTemp = mergeSort(right);
var result = merge(leftTemp, rightTemp)
result
}
}
def merge(left: ArrayBuffer[Int], right: ArrayBuffer[Int]): ArrayBuffer[Int] = {
var result = ArrayBuffer[Int]()
while (left.size > 0 || right.size > 0) {
if (left.size > 0 && right.size > 0) {
if (left(0) <= right(0)) {
result += left(0)
left.remove(0)
} else {
result += right(0)
right.remove(0)
}
} else if (left.size > 0) {
result += left(0)
left.remove(0)
} else if (right.size > 0) {
result += right(0)
right.remove(0)
}
}
result
}
}
MergeSortObject.scala
import scala.collection.mutable.ArrayBuffer
object MergeSortObject {
def main(args: Array[String]): Unit = {
val array = ArrayBuffer(10, 5, 15, 25, 7, 11, 17, 35, 34, 16)
for (i <- 0 to array.length - 1) {
print(array(i))
if (i == array.length - 1) {
} else {
print(", ")
}
}
println()
var ms = new MergeSortClass()
//-->>>TheseValues Below
var temp = ms.mergeSort(array)
//ms.test(array) (not shown here)
for (i <- 0 to temp.length - 1) {
print(temp(i))
if (i == temp.length - 1) {
} else {
print(", ")
}
}
}
}