package org.wesome.dsalgo;
public class PushZeroToEnd {
static int[] pushZerosToEnd(int[] arr) {
int count = 0;
int arrLength = arr.length;
/* Iterate the array. If element is non - zero, copy the element at index count */
for (int i = 0; i < arrLength; i++)
if (arr[i] != 0) {
arr[count] = arr[i];
/* increment the count */
count++;
}
/* All the non-zero elements are moved to start, Iterate the array again and fill remaining places with 0 */
while (count < arrLength) {
arr[count++] = 0;
}
return arr;
}
}
package org.wesome.dsalgo;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import static org.wesome.dsalgo.PushZeroToEnd.pushZerosToEnd;
class PushZeroToEndTest {
@Test
void pushZerosToEndTest1() {
int[] arr = {1, 4, 0, 0, 2, 0, 6, 0, 9};
int[] ints = pushZerosToEnd(arr);
int[] assertArrayEquals = {1, 4, 2, 6, 9, 0, 0, 0, 0};
Assertions.assertArrayEquals(assertArrayEquals, ints);
}
@Test
void pushZerosToEndTest2() {
int[] arr = {0, 0, 0, 0, 0};
int[] ints = pushZerosToEnd(arr);
int[] assertArrayEquals = {0, 0, 0, 0, 0};
Assertions.assertArrayEquals(assertArrayEquals, ints);
}
@Test
void pushZerosToEndTest3() {
int[] arr = {0, 0, -3, -2, -1};
int[] ints = pushZerosToEnd(arr);
int[] assertArrayEquals = {-3, -2, -1, 0, 0};
Assertions.assertArrayEquals(assertArrayEquals, ints);
}
}
plugins {
id 'java'
}
group 'org.wesome'
version '1.0-SNAPSHOT'
repositories {
mavenCentral()
}
dependencies {
testImplementation('org.junit.jupiter:junit-jupiter:5.6.2')
}
test {
useJUnitPlatform()
}