This is the Java Program to Shift the 0’s in an Array to the End.
Given an array of integers, shift all the zeroes present in it to the end.
Example:
Array = [1 0 2 3 0 4]
Output
Array = [1 2 3 4 0 0]
Traverse the array from beginning to end, and whenever a nonzero is encountered, move it to the position of the first element having a zero value, in the array.
Here is the source code of the Java Program to Shift the 0’s in an Array to the End. 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 End
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class ShiftZeroesEnd {
// Function to shift the zeroes in the end
static void inTheEnd(int[] array){
int startIndex = 0;
int i,j,temp;
for(i=0;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 user input and display the output
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;
}
}
inTheEnd(array);
System.out.println("The array after shifting the zeroes in the end is");
for(i=0; i<array.length; i++){
System.out.print(array[i] + " ");
}
}
}
1. In function inTheEnd(), 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 non-zero elements.
3. Any non-zero element is shifted to the position of the first zero element using the nested loop for(j=i;j>startIndex;j–).
4. Consequently, all the zeroes get shifted to the end 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 end is 1 2 3 4 0 0 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 end is 6 7 8 9 0 0
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