Last active
December 25, 2015 10:49
-
-
Save ravichandrae/6964374 to your computer and use it in GitHub Desktop.
This program moves all the zeros to the end of array.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Created with IntelliJ IDEA. | |
* User: Ravi | |
* Date: 10/13/13 | |
* Time: 9:56 PM | |
* To change this template use File | Settings | File Templates. | |
*/ | |
public class MoveZerosDemo { | |
public static void main(String[] args) | |
{ | |
int[] array = {6,0,1,0,0,4,3,0,5,2}; | |
moveZerosToEnd( array ); | |
for( int i = 0; i < array.length; i++ ) | |
{ | |
System.out.print( array[i] + " "); | |
} | |
} | |
public static void moveZerosToEnd(int[] array) | |
{ | |
int resInd = 0;// to keep track of non-zero elements in the final array | |
int i; | |
for( i = 0; i < array.length; i++ ) | |
{ | |
if( array[i] > 0 ) | |
{ | |
if( i != resInd ) //Avoid self copy | |
array[resInd] = array[i]; | |
resInd++; | |
} | |
} | |
//Fill the remaining entries with 0 | |
while( resInd < array.length ) | |
{ | |
array[resInd] = 0; | |
resInd++; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment