Topic description:
Given an array, without applying for a new array , put non-zero elements in the array stably at the front of the array, and zero elements in the back of the array. Stability means that the relative positions of non-zero elements do not change. The topic is very simple, let's talk about the blog.
Problem solving plan:
The first method is similar to the method such as insertion sort. It traverses the array and moves it forward if it encounters a non-zero element until the previous element is not 0 or to the top of the array.
The second method, with fewer operations, uses an auxiliary subscript starting from zero, traverses the array, and if a non-zero element is encountered, it is assigned to the position of the auxiliary subscript, and then the auxiliary subscript is added.
Code:
import java.util.Scanner; public class FirstQues { public static void main(String[] args) { Scanner in = new Scanner(System.in); int num = in.nextInt(); int[] primaryArr = new int[num]; for(int i=0; i<num; i++){ primaryArr[i] = in.nextInt(); } // settleArr1(primaryArr); settleArr2(primaryArr); for(int q=0; q<primaryArr.length; q++){ System.out.print(primaryArr[q] + " "); } } public static void settleArr1(int[] primaryArr){ boolean flag=false; for(int x=1; x<primaryArr.length; x++){ // if the value of x at this position is not 0 if(primaryArr[x]!=0){ // and there is 0 in front of it, move the current position forward until it is not 0 or to the top of the array for(int j= x-1; primaryArr[j]==0 && j>=0; j--){ primaryArr[j] = primaryArr[j+1]; // The current position moves forward, then this position should be filled with 0 primaryArr[j+1] = 0; // If j is 0, it cannot be subtracted, otherwise the array will be out of bounds if(j==0) break; } } } } public static void settleArr2(int[] primaryArr){ int index =0; for(int i =0 ; i<primaryArr.length; i++){ if(primaryArr[i]!=0){ primaryArr[index]= primaryArr[i]; if(index != i) primaryArr[i] = 0; index++; } } } }
Test Results: