Arrays: Program to move all 0's to the end of an array



Given an array, move all the 0s at the end of the given array
For example, int[] array = { 2, 0, 4, 1, 0, 0, 8, 6, 0, 9}
After moving all the 0's at the end, the resulting array will be
int[] array = { 2, 4, 1, 8, 6, 9, 0, 0, 0, 0}

 
Approach
  1. The idea is to use 0 as the pivot element and check if we have a non zero element we will swap it with the pivot element
  2. Traverse through the array and maintain the pointer
  3. Check for the element , if the element is zero then swap the current element with the element at the pointer. After the swap increment the pointer
  4. By this we will get the non zero elements at the beginning of the array and all zeros at the end of the array
 
Complexity

Time Complexity : O(n) , where n is the number of elements in the array
Space Complexity: O(1)

 

Java Code
class MoveZeroToEnd{

        public static void swap(int[] arr, int a, int b){
            int temp = arr[a];
            arr[a] = arr[b];
            arr[b] = temp;
        }
    
        public void moveZeroToEnd(int[] arr){
            int j=0;
            for (int i = 0; i < arr.length; i++) {
                if (arr[i] != 0) {
                    // Swap - arr[j] & arr[i]
                    swap(arr, j, i); // 
                    j++;
                }
            }
        }
    
        public static void main(String[] args){
            
            int[] arr = { 2, 9, 0, 7, 6, 0, 5, 0, 1 };
            int n = arr.length;
            
            System.out.print("Input array : ");
            for	 (int i = 0; i < n; i++){
                System.out.print(arr[i]+" ");
            }
            System.out.println();
            MoveZeroToEnd mz = new MoveZeroToEnd();
            
            mz.moveZeroToEnd(arr);
            
            System.out.print("Output array : ");
            for (int i = 0; i < n; i++) {
                System.out.print(arr[i] + " "); 
            }
      }
 } 
 
Output

Input array : 2 9 0 7 6 0 5 0 1
Output array : 2 9 7 6 5 1 0 0 0



Thanks for feedback.



Read More....
Check if an array is a min heap
Convert a sorted array into a binary search tree - recursive approach
Print the elements of an array
Find the kth largest element in the array
Find the kth smallest element in the array
Merge two sorted arrays