w3resource

Scala Programming: Segregate all 0s on left side and all 1s on right side of a given array of 0s and 1s

Scala Programming Array Exercise-28 with Solution

Write a Scala program to segregate all 0s on left side and all 1s on right side of a given array of 0s and 1s.

Sample Solution:

Scala Code:

object Scala_Array {

  def main(args: Array[String]): Unit = {
    val nums = Array(0, 1, 0, 1, 1, 0, 1, 1, 0, 0, 1);
    val i = 0
    val nums_size = nums.length;
    var left = 0
    var right = nums_size - 1;

    println("Original array:")
    for (x <- nums) {
      print(s"${x}, ")
    }

    while (left < right) {
      /* While  0 at left increment left index  */
      while (nums(left) == 0 && left < right) left += 1;

      /* While we see 1 at right decrement right index*/
      while (nums(right) == 1 && left < right) right -= 1;

      if (left < right) {
        nums(left) = 0;
        nums(right) = 1;
        left += 1;
        right += 1;
      }
    }

    System.out.println("\nArray after segregation array becomes:");
    for (x <- nums) {
      print(s"${x}, ")
    }
  }
}

Sample Output:

Original array:
0, 1, 0, 1, 1, 0, 1, 1, 0, 0, 1, 
Array after segregation array becomes:
0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1,

Scala Code Editor :

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

Previous: Write a Scala program to find smallest and second smallest elements of a given array.
Next: Write a Scala program to find the two elements from a given array of positive and negative numbers such that their sum is closest to zero.

What is the difficulty level of this exercise?