Java shift all zero's to start of array
- In Java we can shift all zeros in array to start/left of array using for loop.
public class shiftZerosToStart {
public static void main(String[] args) {
int arr[] = { 0,1,3,40,-4,-6,0,7,0,-6};
int temp; // creating temp variable
for (int i = arr.length - 1; i >= 0; i--) { // loop start from last index position
for (int j = i - 1; j >= 0; j--) {
if (arr[i] == 0) { // condition to check if value is 0 in array
// logic for swapping
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
System.out.println("Array after pushing zeros to the start of array: ");
for (int n : arr) {
System.out.print(n + " ");
}
}
}
Output:
|
Java shift all zero's to start of array |
- We can also achieve this by using for loops
public class shiftZerosToStart {
public static void main(String[] args) {
int arr[] = { 0,1,3,40,-4,-6,0,7,0,-6};
int[] b=new int[arr.length];
int start=0;
int end=b.length-1;
//loop-for storing 0's at start of array
for(int i=0;i<arr.length;i++) {
if(arr[i]==0) {
b[start]=arr[i];
start++;
}
}
//loop-for storing values other than 0's after 0's filled in array
for(int j=0;j<arr.length;j++) {
if(arr[j]!=0) {
b[start]=arr[j];
start++;
}
}
System.out.println("Array after pushing zeros to the start of array: ");
for (int n : b) {
System.out.print(n + " ");
}
}
}
Output:
|
Java shift all zero's to start of array |
Please comment below to feedback or ask questions.
No comments:
Post a Comment
Please comment below to feedback or ask questions.