Q:

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

0

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.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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,

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Similar questions


need a help?


find thousands of online teachers now