 # moveZero

Feb 9th, 2022
1,221
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
1. /*Array Sort
2. Given an array integers, write a program that moves all of the zeroes to the end of it,
3. while maintaining the relative order of the non-zero elements.
4.
5. Input
6. Read from the standard input:
7. There is one line of input, containing N amount of integers, seperated by a comma (",")*/
8. /*Output
9. Print to the standard output:
10.
11. There is one line of outpit, containing the sorted integers, seperated by a comma (",")
12. Constraints
13. 5 <= N <= 1000*/
14. /*Sample Tests
15. Input
16. 0,1,0,3,12
17. Output
18. 1,3,12,0,0
19. Input
20. 0,0,0,5,0,3,2,3
21. Output
22. 5,3,2,3,0,0,0,0*/
23. let input =['0','0','0','5','0','3','2','3'];
24. //let input =['0','1','0','3','12'];
25. let print = this.print || console.log;
26. let gets = this.gets || ((arr, index) => () => arr[index++])(input, 0);
27.
28.
29. let count = 0;// Count of non-zero elements
30. function pushZero (arr ,n){
31.     // Traverse the array. If element encountered is non-
32.     // zero, then replace the element at index 'count'
33.     // with this element
34. for(let i=0;i<n;i++){
35.     if (arr[i] !=0){
36.         arr[count++] = arr[i]; // here count is
37.         // incremented
38.         // Now all non-zero elements have been shifted to
39.         // front and 'count' is set as index of first 0.
40.         // Make all elements 0 from count to end.
41.     }
42. }
43. while (count<n) {
44.     arr[count++] = 0;
45. }
46. }
47.
48.    // Driver code
49.    let arr =[0,0,0,5,0,3,2,3];
50.    //let arr = [0,1,0,3,12];
51.    let n = arr.length;
52.    pushZero(arr, n);
53.    print(arr.join(','));
54.
55.