Click here to Skip to main content
15,868,016 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Given a random integer array, push all the zeros that are present to end of the array. The respective order of other elements should remain same.
Change in the input array itself. You don't need to return or print elements. Don't use extra array.
Note : You need to do this in one scan of array only.
Input format :

What I have tried:

C++
public class PushZerosAtEnd {
	
	public static void pushZerosAtEnd(int[] arr){
              int [] temp= new int[arr.length];
		      int i=0;
		      int k=0;
		      while(i<arr.length && k<temp.length){
		        if(arr[i]!=0){
		          temp[k]=arr[i];
		          i++;
		          k++;
		        }
		        else{
		          i++;
		        }
		      }
      for(int l=0;l<arr.length;l++){
       System.out.print(arr[l] + " ");
	}

	}
}


I don't know why is this returning the, whereas debugging is good
Posted
Updated 6-May-18 5:16am
v2
Comments
Richard MacCutchan 5-May-18 14:02pm    
Your question is missing some details
CPallini 6-May-18 12:19pm    
I guess you cannot satisfy all the requirements.

This would be my algorithm :
C++
for each n in array :
   if array[n] is zero then
      move all items in array after n forward
      set last item in array to zero  //(ie., array[last] = 0)
   endif
endfor
The function memmove is handy for moving blocks of memory.
 
Share this answer
 
Comments
KarstenK 6-May-18 13:24pm    
He is using Java so he cant use memmove.
Rick York 7-May-18 11:21am    
Yes, that looks like java code but his question has a C++ tag. I would guess it shouldn't have that tag. Regardless, memmove is certainly not a requirement but it eliminates the need for any other loop traversals. Of course, with a flag or two and some intelligence only one loop is required, including the moves.
Quote:
I don't know why is this returning the, whereas debugging is good

That is impossible, you can't get a correct result because the code is wrong.
Reread your code and pay attention to what you do with temp.

Your requirement say:
Quote:
Change in the input array itself. You don't need to return or print elements. Don't use extra array.

but you are using a new array temp. Try to change your code accordingly, it is not really complicated.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900