VOOZH about

URL: https://www.geeksforgeeks.org/dsa/move-zeroes-end-array-set-2-using-single-traversal/

⇱ Move all zeroes to end of array | Set-2 (Using single traversal) - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Move all zeroes to end of array | Set-2 (Using single traversal)

Last Updated : 2 Aug, 2022

Given an array of n numbers. The problem is to move all the 0's to the end of the array while maintaining the order of the other elements. Only single traversal of the array is required.
Examples: 
 

Input : arr[] = {1, 2, 0, 0, 0, 3, 6}
Output : 1 2 3 6 0 0 0

Input: arr[] = {0, 1, 9, 8, 4, 0, 0, 2, 7, 0, 6, 0, 9}
Output: 1 9 8 4 2 7 6 9 0 0 0 0 0


 


Algorithm: 
 

moveZerosToEnd(arr, n)
 Initialize count = 0
 for i = 0 to n-1
 if (arr[i] != 0) then
 arr[count++]=arr[i]
 for i = count to n-1
 arr[i] = 0
👁 Image
Flowchart


 


Output
Original array: 0 1 9 8 4 0 0 2 7 0 6 0 9 
Modified array: 1 9 8 4 2 7 6 9 0 0 0 0 0 


Time Complexity: O(n). 
Auxiliary Space: O(1).
 

Comment
Article Tags: