w3resource

Scala Programming: Separate even and odd numbers of a given array of integers

Scala Programming Array Exercise-33 with Solution

Write a Scala program to separate even and odd numbers of a given array of integers. Put all even numbers first, and then odd numbers.

Sample Solution:

Scala Code:

object Scala_Array {

  def test(arr: Array[Int]): Array[Int] = {
    var left_side = 0
    var right_side = arr.length - 1;
    while (left_side < right_side) {
      while (arr(left_side) % 2 == 0 && left_side < right_side) left_side += 1;
      while (arr(right_side) % 2 == 1 && left_side < right_side) right_side -= 1;
      if (left_side < right_side) {
        val temp = arr(left_side);
        arr(left_side) = arr(right_side);
        arr(right_side) = temp;
        left_side += 1;
        right_side -= 1;
      }
    }
    arr;
  }

  def main(args: Array[String]): Unit = {
    val nums = Array(20, 12, 23, 17, 7, 8, 10, 2, 1);

    println("\nOriginal Array elements:")
    // Print all the array elements
    for (x <- nums) {
      print(s"${x}, ")
    }

    //println(Arrays.toString(nums));
    val result = test(nums);
    println("\nArray, after separating even and odd numbers:");
    // Print all the array elements
    for (x <- result) {
      print(s"${x}, ")
    }
  }
}

Sample Output:

Original Array elements:
20, 12, 23, 17, 7, 8, 10, 2, 1, 
Array, after separating even and odd numbers:
20, 12, 2, 10, 8, 7, 17, 23, 1, 

Scala Code Editor :

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Java program to arrange the elements of a given array of integers where all positive integers appear before all the negative integers.
Next: Write a Scala program to replace every element with the next greatest element (from right side) in a given array of integers. There is no element next to the last element, therefore replace it with -1.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.