Move all Zeroes to the End of the Array

How to Move All Zeroes Present in an Array to the End in Java?

In this tutorial, we will learn about the topic i.e. Move all zeroes present in an array to the end in Java. In Java, an array is an object that stores values of the same data type. It is a non-primitive data type which means it is not one of the fundamental data types provided by the Java programming language.

Different ways to move all Zeroes to the end of the Array

  1. Move all zeroes By Using Sorting.
  2. Move all zeroes Using Manual Iteration and Replacement.

1. Move all zeroes by Using Sorting

Moving all zeroes present in an array to the end using sorting in Java. It refers to rearranging the elements of the array in such a way that all zeroes are placed at the end of the array while preserving the relative order of the non-zero elements. This approach will use a sorting algorithm to sort the array and ensure that zeroes are moved to the end during the sorting process.

  • Start with an input array that contains both zero and non-zero elements.
  • Apply a sorting algorithm to rearrange the elements of the array.
  • Modify the sorting algorithm logic to ensure that during the sorting process, zeroes are moved to the end of the array instead of being sorted with the other elements.
  • After the sorting is complete, all the zeroes will be positioned at the end of the array, while the non-zero elements will maintain their original relative order.
  • Optionally, if required, perform additional operations on the sorted array to process the zero elements separately or fulfill any other requirements.

Algorithm:

  • Initialize two pointers, left and right, pointing to the start and end of the array, respectively.
  • Iterate through the array while left < right.
    • If arr[left] is non-zero, increment left.
    • If arr[left] is zero and arr[right] is non-zero, swap arr[left] and arr[right]. Then, increment left and decrement right.
    • If both arr[left] and arr[right] are zero, decrement right.
  • After the iteration, all non-zero elements are on the left side of the array, and all zeroes are on the right side.
  • Iterate through the array starting from left to the end of the array and set all elements to zero.

Example:

import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] arr = {1, 0, 5, 0, 3, 0, 8};

System.out.println("Before sorting: " + Arrays.toString(arr));
moveZeroesToEnd(arr);
System.out.println("After sorting: " + Arrays.toString(arr));
}

public static void moveZeroesToEnd(int[] arr) {
int n = arr.length;
boolean swapped;

for (int i = 0; i < n - 1; i++) {
swapped = false;
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] == 0) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
swapped = true;
}
}
// If no elements were swapped in the inner loop, the array is already sorted
if (!swapped)
break;
}
int countZeroes = 0;
for (int i = n - 1; i >= 0; i--) {
     if (arr[i] == 0) {
         countZeroes++;
         arr[i] = arr[n - countZeroes];
         arr[n - countZeroes] = 0;
     }
}
}
}


Output:

Before sorting: [1, 0, 5, 0, 3, 0, 8]
After sorting: [1, 5, 3, 8, 0, 0, 0]

In this example, the “moveZeroesToEnd” method performs the sorting with zero elements moved to the end. Here we are using the Bubble Sort algorithm to sort elements. Finally, the method counts the number of zeroes and sets the remaining elements at the end of the array to 0.

2. Move all zeroes Using Manual Iteration and Replacement

In this approach, array elements will be initialized in the program. Then as per the algorithm push all non-zero elements on the left side of an array with the zero-element remaining in the end.

Algorithm:

  • Initialize two pointers, writePointer and readPointer, both starting from the beginning of the array.
  • Iterate through the array using the readPointer.
  • If the element at the readPointer is not zero, replace the element at the writePointer with the element at the readPointer and increment both pointers.
  • If the element at the readPointer is zero, only increment the readPointer.
  • After iterating through the array, set all elements from the writePointer to the end of the array to 0.

Example:

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        int[] arr = {1, 0, 5, 0, 3, 0, 8};
        System.out.println("Before moving zeroes: " + Arrays.toString(arr));
        moveZeroesToEnd(arr);
        System.out.println("After moving zeroes: " + Arrays.toString(arr));
    }

    public static void moveZeroesToEnd(int[] arr) {
        int writePointer = 0;
        int readPointer = 0;
        // Move non-zero elements to the front
        while (readPointer < arr.length) {
            if (arr[readPointer] != 0) {
                arr[writePointer] = arr[readPointer];
                writePointer++;
            }
            readPointer++;
        }
        // Set remaining elements to 0
        while (writePointer < arr.length) {
            arr[writePointer] = 0;
            writePointer++;
        }
    }
}


Output:

Before moving zeroes: [1, 0, 5, 0, 3, 0, 8]
After moving zeroes: [1, 5, 3, 8, 0, 0, 0]

In this example, the moveZeroesToEnd method moves all zeroes to the end of the array using manual iteration and replacement. It uses two pointers, writePointer and readPointer, to iterate through the array. Non-zero elements are replaced at the writePointer, and both pointers are incremented. After iterating through the array, the remaining elements from the writePointer to the end of the array are set to 0.

Discover Our Exciting Courses and Quiz

Enroll now to enhance your skills and knowledge!

Java Online Quiz

Level up your coding skills with our interactive programming quiz!