Python3 Program to Move all zeroes to end of array | Set-2 (Using single traversal)
Last Updated :
17 Jan, 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
swap(arr[count++], arr[i])
Â
Python3
def moveZerosToEnd (arr, n):
count = 0 ;
for i in range ( 0 , n):
if (arr[i] ! = 0 ):
arr[count], arr[i] = arr[i], arr[count]
count + = 1
def printArray(arr, n):
for i in range ( 0 , n):
print (arr[i],end = " " )
arr = [ 0 , 1 , 9 , 8 , 4 , 0 , 0 , 2 ,
7 , 0 , 6 , 0 , 9 ]
n = len (arr)
print ( "Original array:" , end = " " )
printArray(arr, n)
moveZerosToEnd(arr, n)
print ("
Modified array: ", end=" ")
printArray(arr, n)
|
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).
Â
Please refer complete article on Move all zeroes to end of array | Set-2 (Using single traversal) for more details!
Share your thoughts in the comments
Please Login to comment...