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:
need an explanation for this answer? contact us directly to get an explanation for this answer