Java Program to Move All Zeros to the Start of an Array

«
»

This is the Java Program to Shift the 0’s in an Array to the Beginning.

Problem Description

Given an array of integers, shift all the zeroes present in it to the beginning.
Example:

advertisement

Array = [1 0 2 3 0 4]

Output
Array = [0 0 1 2 3 4]

Problem Solution

Traverse the array from beginning to end, and whenever a zero is encountered, move it to the position of the first nonzero element, in the array.

Program/Source Code
advertisement
advertisement

Here is the source code of the Java Program to Shift the 0’s in an Array to the Beginning. The program is successfully compiled and tested using IDE IntelliJ Idea in Windows 7. The program output is also shown below.

  1.  
  2. //Java Program to Shift the 0's in an Array to the Beginning
  3.  
  4. import java.io.BufferedReader;
  5. import java.io.InputStreamReader;
  6.  
  7. public class ShiftZeroesBeginning {
  8.     // Function to shift 0's in the beginning
  9.     static void inTheBeginning(int[] array){
  10.              int startIndex=0;
  11.              int i,temp,j;
  12.              for(i=1; i<array.length; i++){
  13.                  if(array[i] == 0){
  14.                      for(j=i; j>startIndex;j--){
  15.                          temp = array[j];
  16.                          array[j] = array[j-1];
  17.                          array[j-1] = temp;
  18.                      }
  19.                      startIndex++;
  20.                  }
  21.              }
  22.         }
  23.     // Function to read input and display the final array
  24.     public static void main(String[] args){
  25.             BufferedReader br = new BufferedReader
  26.                                 (new InputStreamReader(System.in));
  27.             int size;
  28.             System.out.println("Enter the size of the array");
  29.             try {
  30.                 size = Integer.parseInt(br.readLine());
  31.             } catch (Exception e) {
  32.                 System.out.println("Invalid Input");
  33.                 return;
  34.             }
  35.             int[] array = new int[size];
  36.             System.out.println("Enter array elements");
  37.             int i;
  38.             for (i = 0; i < array.length; i++) {
  39.                 try {
  40.                     array[i] = Integer.parseInt(br.readLine());
  41.                 } catch (Exception e) {
  42.                     System.out.println("An error occurred");
  43.                     return;
  44.                 }
  45.             }
  46.             inTheBeginning(array);
  47.             System.out.println("The array after shifting the" +
  48.                                 " zeroes in the beginning is");
  49.             for(i=0; i<array.length; i++){
  50.                 System.out.print(array[i] + " ");
  51.             }
  52.         }
  53. }
Program Explanation

1. In function inTheBeginning(), the loop for(i=0;i<array.length;i++) is used to iterate through the array.
2. The statement if(array[i]==0) looks for elements whose value is zero.
3. Any zero element is shifted to the position of the first non-zero element using the nested loop for(j=i;j>startIndex;j–).
4. The variable startIndex serves as the position of first non-zero element.
5. Consequently, all the zeroes get shifted to the beginning of the array.

advertisement

Time Complexity: O(n2) where n is the number of elements in the array.

Runtime Test Cases
 
Case 1 (Simple test Case):
 
Enter the size of the array
6
Enter array elements
1
0
2
3
0
4
The array after shifting the zeroes in the beginning is
0 0 1 2 3 4
 
Case 2 (Simple test Case - another example):
 
Enter the size of the array
6
Enter array elements
6
7
8
9
0
0
The array after shifting the zeroes in the beginning is
0 0 6 7 8 9

Sanfoundry Global Education & Learning Series – Java Programs.

advertisement

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & technical discussions at Telegram SanfoundryClasses.