This is the Java Program to Shift the 0’s in an Array to the Beginning.
Given an array of integers, shift all the zeroes present in it to the beginning.
Example:
Array = [1 0 2 3 0 4]
Output
Array = [0 0 1 2 3 4]
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.
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.
//Java Program to Shift the 0's in an Array to the Beginning
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class ShiftZeroesBeginning {
// Function to shift 0's in the beginning
static void inTheBeginning(int[] array){
int startIndex=0;
int i,temp,j;
for(i=1; i<array.length; i++){
if(array[i] == 0){
for(j=i; j>startIndex;j--){
temp = array[j];
array[j] = array[j-1];
array[j-1] = temp;
}
startIndex++;
}
}
}
// Function to read input and display the final array
public static void main(String[] args){
BufferedReader br = new BufferedReader
(new InputStreamReader(System.in));
int size;
System.out.println("Enter the size of the array");
try {
size = Integer.parseInt(br.readLine());
} catch (Exception e) {
System.out.println("Invalid Input");
return;
}
int[] array = new int[size];
System.out.println("Enter array elements");
int i;
for (i = 0; i < array.length; i++) {
try {
array[i] = Integer.parseInt(br.readLine());
} catch (Exception e) {
System.out.println("An error occurred");
return;
}
}
inTheBeginning(array);
System.out.println("The array after shifting the" +
" zeroes in the beginning is");
for(i=0; i<array.length; i++){
System.out.print(array[i] + " ");
}
}
}
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.
Time Complexity: O(n2) where n is the number of elements in the array.
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.
- Check Programming Books
- Practice BCA MCQs
- Apply for Java Internship
- Practice Information Technology MCQs
- Apply for Computer Science Internship