Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*Array Sort
- Given an array integers, write a program that moves all of the zeroes to the end of it,
- while maintaining the relative order of the non-zero elements.
- Input
- Read from the standard input:
- There is one line of input, containing N amount of integers, seperated by a comma (",")*/
- /*Output
- Print to the standard output:
- There is one line of outpit, containing the sorted integers, seperated by a comma (",")
- Constraints
- 5 <= N <= 1000*/
- /*Sample Tests
- Input
- 0,1,0,3,12
- Output
- 1,3,12,0,0
- Input
- 0,0,0,5,0,3,2,3
- Output
- 5,3,2,3,0,0,0,0*/
- let input =['0','0','0','5','0','3','2','3'];
- //let input =['0','1','0','3','12'];
- let print = this.print || console.log;
- let gets = this.gets || ((arr, index) => () => arr[index++])(input, 0);
- let count = 0;// Count of non-zero elements
- function pushZero (arr ,n){
- // Traverse the array. If element encountered is non-
- // zero, then replace the element at index 'count'
- // with this element
- for(let i=0;i<n;i++){
- if (arr[i] !=0){
- arr[count++] = arr[i]; // here count is
- // incremented
- // Now all non-zero elements have been shifted to
- // front and 'count' is set as index of first 0.
- // Make all elements 0 from count to end.
- }
- }
- while (count<n) {
- arr[count++] = 0;
- }
- }
- // Driver code
- let arr =[0,0,0,5,0,3,2,3];
- //let arr = [0,1,0,3,12];
- let n = arr.length;
- pushZero(arr, n);
- print(arr.join(','));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement