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.
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,
total answers (1)
start bookmarking useful questions and collections and save it into your own study-lists, login now to start creating your own collections.
Sample Output:
need an explanation for this answer? contact us directly to get an explanation for this answer