Answers for "Move Zeros to the End array"

1

Move Zeros to the End array

Array -- Move Zeros to the End
Write a method that can move all the zeros to  last indexes of 
the array (Do Not Use Sort Method)
Ex:
input:  {1,0,2,0,3,0,4,0};
output: [1, 2, 3, 4, 0, 0, 0, 0]
 
Solution:
public static int[] moveZeros( int[]  arr ) {
ArrayList<Integer> list = new ArrayList<>();
int countZero = 0;
for(int each: arr) {
list.add(each);
countZero+= (each==0)?1:0;
}

list.removeAll(Arrays.asList(0));
arr = new int[arr.length];
for(int i=0; i <arr.length-countZero; i++ ) {
arr[i] = list.get(i);
}
return arr;
}
Posted by: Guest on September-29-2021
0

Move all zeros present in an array to the end

def swap(A, i, j):
 
    temp = A[i]
    A[i] = A[j]
    A[j] = temp
 
 
# Function to move all zeros present in a list to the end
def partition(A):
 
    j = 0
 
    # each time we encounter a non-zero, `j` is incremented, and
    # the element is placed before the pivot
    for i in range(len(A)):
        if A[i]:            # pivot is 0
            swap(A, i, j)
            j = j + 1
Posted by: Guest on February-02-2021

Code answers related to "Move Zeros to the End array"

Browse Popular Code Answers by Language