Skip to content
This repository has been archived by the owner on Jul 10, 2024. It is now read-only.

Commit

Permalink
Move all zeros in Scala (#5730)
Browse files Browse the repository at this point in the history
Co-authored-by: Riyazul555 <riyazulislam2003@gmail.com>
Co-authored-by: Anandha Krishnan S <anandajith@gmail.com>
  • Loading branch information
3 people authored Jun 25, 2024
1 parent 4f003fd commit bcd7257
Showing 1 changed file with 27 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
object MoveZeroesToEnd {
def main(args: Array[String]): Unit = {
val arr = Array(0, 1, 0, 3, 12)
println(s"Original array: ${arr.mkString(", ")}")

moveZeroes(arr)

println(s"Array after moving zeroes: ${arr.mkString(", ")}")
}

def moveZeroes(arr: Array[Int]): Unit = {
var nonZeroIndex = 0

// First, fill in the non-zero elements
for (i <- arr.indices) {
if (arr(i) != 0) {
arr(nonZeroIndex) = arr(i)
nonZeroIndex += 1
}
}

// Then, fill in the remaining positions with zeroes
for (i <- nonZeroIndex until arr.length) {
arr(i) = 0
}
}
}

0 comments on commit bcd7257

Please sign in to comment.