Arrays: Program to move all 0's to the end of an array
Given an array, move all the 0s at the end of the given array
For example, int[] array = { 2, 0, 4, 1, 0, 0, 8, 6, 0, 9}
After moving all the 0's at the end, the resulting array will be
int[] array = { 2, 4, 1, 8, 6, 9, 0, 0, 0, 0}
Approach
- The idea is to use 0 as the pivot element and check if we have a non zero element we will swap it with the pivot element
- Traverse through the array and maintain the pointer
- Check for the element , if the element is zero then swap the current element with the element at the pointer. After the swap increment the pointer
- By this we will get the non zero elements at the beginning of the array and all zeros at the end of the array
Complexity
Time Complexity : O(n) , where n is the number of elements in the array
Space Complexity: O(1)
Java Code
class MoveZeroToEnd{
public static void swap(int[] arr, int a, int b){
int temp = arr[a];
arr[a] = arr[b];
arr[b] = temp;
}
public void moveZeroToEnd(int[] arr){
int j=0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] != 0) {
// Swap - arr[j] & arr[i]
swap(arr, j, i); //
j++;
}
}
}
public static void main(String[] args){
int[] arr = { 2, 9, 0, 7, 6, 0, 5, 0, 1 };
int n = arr.length;
System.out.print("Input array : ");
for (int i = 0; i < n; i++){
System.out.print(arr[i]+" ");
}
System.out.println();
MoveZeroToEnd mz = new MoveZeroToEnd();
mz.moveZeroToEnd(arr);
System.out.print("Output array : ");
for (int i = 0; i < n; i++) {
System.out.print(arr[i] + " ");
}
}
}
Output
Input array : 2 9 0 7 6 0 5 0 1
Output array : 2 9 7 6 5 1 0 0 0
Thanks for feedback.