Monday, January 27, 2025
Google search engine
HomeData Modelling & AIJava Program to Move all zeroes to end of array | Set-2...

Java Program to Move all zeroes to end of array | Set-2 (Using single traversal)

Given an array of n numbers. The problem is to move all the 0’s to the end of the array while maintaining the order of the other elements. Only single traversal of the array is required.
Examples: 
 

Input : arr[]  = {1, 2, 0, 0, 0, 3, 6}
Output : 1 2 3 6 0 0 0

Input: arr[] = {0, 1, 9, 8, 4, 0, 0, 2, 7, 0, 6, 0, 9}
Output: 1 9 8 4 2 7 6 9 0 0 0 0 0

 

Algorithm: 
 

moveZerosToEnd(arr, n)
    Initialize count = 0
    for i = 0 to n-1
        if (arr[i] != 0) then
            swap(arr[count++], arr[i])

 

Java




// Java implementation to move 
// all zeroes at the end of array
import java.io.*;
  
class GFG {
  
// function to move all zeroes at
// the end of array
static void moveZerosToEnd(int arr[], int n) {
      
    // Count of non-zero elements
    int count = 0;
    int temp;
  
    // Traverse the array. If arr[i] is 
    // non-zero, then swap the element at 
    // index 'count' with the element at 
    // index 'i'
    for (int i = 0; i < n; i++) {
    if ((arr[i] != 0)) {
        temp = arr[count];
        arr[count] = arr[i];
        arr[i] = temp;
        count = count + 1;
    }
    }
}
  
// function to print the array elements
static void printArray(int arr[], int n) {
    for (int i = 0; i < n; i++)
    System.out.print(arr[i] + " ");
}
  
// Driver program to test above
public static void main(String args[]) {
    int arr[] = {0, 1, 9, 8, 4, 0, 0, 2,
                         7, 0, 6, 0, 9};
    int n = arr.length;
  
    System.out.print("Original array: ");
    printArray(arr, n);
  
    moveZerosToEnd(arr, n);
  
    System.out.print("
Modified array: ");
    printArray(arr, n);
}
}
  
// This code is contributed by Nikita Tiwari.


Output: 
 

Original array: 0 1 9 8 4 0 0 2 7 0 6 0 9 
Modified array: 1 9 8 4 2 7 6 9 0 0 0 0 0

Time Complexity: O(n). 
Auxiliary Space: O(1).
 

Please refer complete article on Move all zeroes to end of array | Set-2 (Using single traversal) for more details!

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

Commit to GfG’s Three-90 Challenge! Purchase a course, complete 90% in 90 days, and save 90% cost click here to explore.

Last Updated :
17 Jan, 2022
Like Article
Save Article


Previous

<!–

8 Min Read | Java

–>


Next


<!–

8 Min Read | Java

–>

Share your thoughts in the comments

RELATED ARTICLES

Most Popular

Recent Comments