How to merge two lists in Scala

1 Answer

0 votes
import scala.collection.mutable.ListBuffer

object MergeTwoListsIntoOne_Scala {

  def mergeTwoListsIntoOne(num1: List[Int], num2: List[Int]): List[Int] = {
    val numbers = ListBuffer.empty[Int]
    var i = 0
    var j = 0

    while (i < num1.length && j < num2.length) {
      if (num1(i) <= num2(j)) {
        numbers += num1(i)
        i += 1
      } else {
        numbers += num2(j)
        j += 1
      }
    }

    while (i < num1.length) {
      numbers += num1(i)
      i += 1
    }

    while (j < num2.length) {
      numbers += num2(j)
      j += 1
    }

    numbers.toList
  }

  def main(args: Array[String]): Unit = {
    val num1 = List(7, 3, 2, 9, 1)
    val num2 = List(5, 8, 6, 4, 0, 11, 10, 12)

    val numbers = mergeTwoListsIntoOne(num1, num2)

    println(numbers)
  }
}



/*
run:

List(5, 7, 3, 2, 8, 6, 4, 0, 9, 1, 11, 10, 12)

*/

 



answered Oct 9, 2024 by avibootz
...